如何从列表中提取特定的键值对并将其添加到数据框?

时间:2019-08-01 23:59:17

标签: python pandas list dataframe

我正在使用JSON格式的数据框(read_json)。我需要从dataframe列之一内部的列表列表中提取特定值,并将其附加为新列。

我的DF:

df_with_name.info()
<class 'pandas.core.frame.DataFrame'>
Index: 286 entries, 500px to youtube.com
Data columns (total 7 columns):
documents    286 non-null object
logo         286 non-null object
name         286 non-null object
points       286 non-null object
rated        286 non-null object
see          2 non-null object
slug         286 non-null object
dtypes: object(7)
memory usage: 27.9+ KB

列中包含列表的列表,我可以像这样访问列表:

df_with_name['points'][4]

从df_with_name的第三列打印列点。

输出:

[{'description': '“500px reserves the right, at its sole discretion, to modify or replace the terms at any time. If the alterations constitute a material change to the terms, 500px will notify you by Posting an announcement on the site. What constitutes a material change will be Determined at 500px’s sole discretion.”',
  'discussion': 'https://edit.tosdr.org/points/995',
  'id': '995',
  'point': 'bad',
  'score': 70,
  'title': ' Terms may be changed any time at their discretion, without notice to the user '},
 {'description': '“500px may terminate your store account at any time for any reason or no reason. All Store Images remaining in your Store account will be removed by 500px upon termination of your store account.”',
  'discussion': 'https://edit.tosdr.org/points/891',
  'id': '891',
  'point': 'bad',
  'score': 60,
  'title': '500px Store: your account can be terminated at any time'}]

我要完成什么:

如何为数据框中的286个条目中的每一个访问键值对 'title','score'和'point' ,并将它们作为新的追加到数据框中列(或从中创建新的数据框)?

我尝试过的事情:

如果我将数据帧中的单个条目指定为字典,则可以访问有趣的键值对,如下所示:

df_as_dict['points'][1]['title']

然后我也可以使用.get()循环,如下所示:

for v in df_as_dict.get('points'):
    print(v.get('title'))

但是,当我尝试将所有内容放在一起或仅在数据帧的片段(单个输入,而不是整个df)上工作时,此操作以某种方式失败。

我想念什么?我的逻辑错在哪里?

1 个答案:

答案 0 :(得分:0)

假设l是您的list

pd.DataFrame(l)