Python 如何访问oneliner中dataframe中的一列字典列表中的值
假设我有数据帧Python 如何访问oneliner中dataframe中的一列字典列表中的值,python,pandas,Python,Pandas,假设我有数据帧 col1 col2 col3 0 [{'a': 1, 'b': 1, 'c': 1}] 1 2 1 [{'a': 2, 'b': 2, 'c': 1}] 2 3 2 [{'a': 3, 'b': 1, 'c': 2}] 4 1 我可以通过以下方式获得过滤后的数据帧: filtered_df = df.iloc[:,[0,2]] 返回 col1
col1 col2 col3
0 [{'a': 1, 'b': 1, 'c': 1}] 1 2
1 [{'a': 2, 'b': 2, 'c': 1}] 2 3
2 [{'a': 3, 'b': 1, 'c': 2}] 4 1
我可以通过以下方式获得过滤后的数据帧:
filtered_df = df.iloc[:,[0,2]]
返回
col1 col3
0 [{'a': 1, 'b': 1, 'c': 1}] 2
1 [{'a': 2, 'b': 2, 'c': 1}] 3
2 [{'a': 3, 'b': 1, 'c': 2}] 1
如果我必须访问dictionary列表中的'c'值,我可以单独遍历col1并附加到list/dictionary。但是,我正在寻找一种pythonic方法,以获得如下输出:
c col3
0 1 2
1 1 3
2 2 1
c col3
0 1 2
1 1 3
2 2 1
使用“按
str编制索引”
作为“选择第一个列表”,然后选择“按以下方式编制索引”c
:
如果需要从第一个列表中创建所有列,请按构造函数创建DataFrame
,也可添加以删除原始列col1
(如有必要):
使用“按
str编制索引”
作为“选择第一个列表”,然后选择“按以下方式编制索引”c
:
如果需要从第一个列表中创建所有列,请按构造函数创建DataFrame
,也可添加以删除原始列col1
(如有必要):
另一个解决方案是: 输出:
另一个解决方案是: 输出:
df = df.join(pd.DataFrame(df.pop('col1').str[0].tolist(), index=df.index))
print (df)
col2 col3 a b c
0 1 2 1 1 1
1 2 3 2 2 1
2 4 1 3 1 2
df['c'] = df.apply(lambda x: x[0][0].get('c'), axis=1)
c col3
0 1 2
1 1 3
2 2 1