访问Pandas DataFrame元素内的列表 [英] Access a list within an element of a Pandas DataFrame

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

问题描述

我有一个熊猫 DataFrame ,其中一列中有一个整数列表。我想访问此列表中的各个元素。我找到了一种方法,方法是使用 tolist()并将其转换回 DataFrame ,但是我我想知道是否有更简单/更好的方法。在此示例中,我将列 A 添加到列 B 中列表的中间元素中。

I have a Pandas DataFrame which has a list of integers inside one of the columns. I'd like to access the individual elements within this list. I've found a way to do it by using tolist() and turning it back into a DataFrame, but I am wondering if there is a simpler/better way. In this example, I add Column A to the middle element of the list in Column B.

import pandas as pd
df = pd.DataFrame({'A' : (1,2,3), 'B': ([0,1,2],[3,4,5,],[6,7,8])})
df['C'] = df['A'] + pd.DataFrame(df['B'].tolist())[1]
df

有更好的方法吗?

推荐答案

更简单的方法是:

df['C'] = df['A'] + df['B'].apply(lambda x:x[1])

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

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