【问题标题】:Iterate key value pairs inside list and convert to pandas dataframe迭代列表内的键值对并转换为熊猫数据框
【发布时间】:2018-06-26 11:10:20
【问题描述】:

我有一些以 格式给出的列表

[{"@context":"ABC","entity":"PQR","URL":"abc@yahoo.com"}]
[{"@context":"RST","entity":"UVW","URL":"efg@gmail.com"}]
.............
............
............

我想把它转换成熊猫数据框:

@context    entity     URL
ABC         PQR        abc@yahoo.com
RST         UVW        efg@gmail.com
...         ...        .......
...         ...        .......

【问题讨论】:

  • df = pd.DataFrame(L) ?
  • 主要问题是 - 什么是输入数据?嵌套列表? csv?
  • 列表是由某些系统生成的?
  • 检查编辑的答案。
  • 你的图片(我们更愿意避免,因为它们不能被复制粘贴)使你的类型看起来很奇怪:你有一个字符串列表,它代表一个元素列表,其元素是字典。对吗?

标签: arrays python-3.x pandas


【解决方案1】:

如果有嵌套列表先把它展平:

from  itertools import chain

L = [[{"@context":"ABC","entity":"PQR","URL":"abc@yahoo.com"}],
     [{"@context":"RST","entity":"UVW","URL":"efg@gmail.com"}]]

df = pd.DataFrame(list(chain.from_iterable(L)))

或者:

df = pd.DataFrame([y for x in L for y in x])

print (df)
  @context            URL entity
0      ABC  abc@yahoo.com    PQR
1      RST  efg@gmail.com    UVW

编辑:

如果数据是由另一个脚本生成的,最好是创建所有字典的列表并传递给 DataFrame 构造函数:

L = [[{"@context":"ABC","entity":"PQR","URL":"abc@yahoo.com"}],
[{"@context":"RST","entity":"UVW","URL":"efg@gmail.com"}]]

L1 = []
for i in L:
    print (i[0])
    #simulate generate dictionaries
    L1.append(i[0])

print (L1)    
[{'@context': 'ABC', 'entity': 'PQR', 'URL': 'abc@yahoo.com'}, 
 {'@context': 'RST', 'entity': 'UVW', 'URL': 'efg@gmail.com'}]


df = pd.DataFrame(L1)
print (df)
  @context            URL entity
0      ABC  abc@yahoo.com    PQR
1      RST  efg@gmail.com    UVW

编辑:

问题是您的数据是字符串,所以首先需要将它们转换为字典列表:

import ast

L = ['[{"@context":"ABC","entity":"PQR","URL":"abc@yahoo.com"}]',
     '[{"@context":"RST","entity":"UVW","URL":"efg@gmail.com"}]']

df = pd.DataFrame([y for x in L for y in ast.literal_eval(x)])
print (df)
  @context            URL entity
0      ABC  abc@yahoo.com    PQR
1      RST  efg@gmail.com    UVW

【讨论】:

  • 代码对我不起作用。请检查附加的 json 结构的 txt 文件(现在我只粘贴了两个)报废输出。我需要提取键 '@context'、'@type'、'url' 作为列作为它们的值作为对应的数据。
  • 抱歉,文件在哪里?
  • @James - 我想我的问题是我看不到你的 scaping 数据的实际代码,可以分享吗?
  • 很抱歉激怒了你。请检查我得到的输出的附加图像
  • df = pd.DataFrame([y for x in L for y in x], , columns=['@context', 'entity', 'URL']) 这段代码对我来说效果很好
猜你喜欢
  • 2019-10-12
  • 2021-07-26
  • 2017-08-26
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多