访问包含列表的Pandas DataFrame列的每个第一个元素 [英] Accessing every 1st element of Pandas DataFrame column containing lists

查看:258
本文介绍了访问包含列表的Pandas DataFrame列的每个第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas DataFrame,其列包含列表对象

I have a Pandas DataFrame with a column containing lists objects

      A
0   [1,2]
1   [3,4]
2   [8,9] 
3   [2,6]

如何访问每个列表的第一个元素并将其保存到DataFrame的新列中?要获得这样的结果:

How can I access the first element of each list and save it into a new column of the DataFrame? To get a result like this:

      A     new_col
0   [1,2]      1
1   [3,4]      3
2   [8,9]      8
3   [2,6]      2

我知道这可以通过遍历每一行来完成,但是有什么"pythonic"方法吗?

I know this could be done via iterating over each row, but is there any "pythonic" way?

推荐答案

您可以使用maplambda函数

df.loc[:, 'new_col'] = df.A.map(lambda x: x[0])

这篇关于访问包含列表的Pandas DataFrame列的每个第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆