简体   繁体   English

如何访问字典列表中的值,该列表是 oneliner 中 dataframe 中的一列

[英]How to access values from lists of dictionary which is a column in dataframe in oneliner

Let's say i have dataframe假设我有 dataframe

     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

I could get the filtered dataframe by:我可以通过以下方式获得过滤后的 dataframe:

filtered_df = df.iloc[:,[0,2]]

returns返回

      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

If i have to access the value for 'c'in the lists of dictionary - i can potentially iterate through the col1 separately and appending to list/dictionary.如果我必须访问字典列表中“c”的值 - 我可以单独遍历 col1 并附加到列表/字典。 However i am looking a pythonic way to be able to get the output as below:但是我正在寻找一种能够获得 output 的pythonic方法,如下所示:

     c   col3
 0   1     2
 1   1     3
 2   2     1

Use indexing by str for select first list and then select c by Series.str.get :使用str索引 select 第一个列表,然后 select c通过Series.str.get

df['c'] = df['col1'].str[0].str.get('c')
print (df)
                         col1  col2  col3  c
0  [{'a': 1, 'b': 1, 'c': 1}]     1     2  1
1  [{'a': 2, 'b': 2, 'c': 1}]     2     3  1
2  [{'a': 3, 'b': 1, 'c': 2}]     4     1  2

If need all columns form first list create DataFrame by constructor, also added DataFrame.pop for remove original column col1 (if necessary):如果需要第一个列表中的所有列,请通过构造函数创建DataFrame ,还添加DataFrame.pop以删除原始列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

Just another solution using df.apply :使用df.apply另一个解决方案:

df['c'] = df.apply(lambda x: x[0][0].get('c'), axis=1)

Output: Output:

     c   col3
 0   1     2
 1   1     3
 2   2     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM