繁体   English   中英

如何将逗号分隔的字典字符串拆分为Pandas数据框

[英]How to Split a comma separated string of dictionaries into a Pandas dataframe

我有以下格式的字符串:

{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}

并希望创建一个数据框,其列标签为“ apple”,“ oranges”,“ x”,并将值放置在它们各自的行中。

我尝试使用此解决方案: Python将逗号分隔的列表转换为熊猫数据框,以及将ast.literal_eval转换为列表,然后再将其转换为数据框,但没有运气。

您的字符串是无效的json ,因此有必要先进行替换:

import ast

s = '{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}'

ss = '[' + s.replace('{', '{"').replace(':"','":"').replace('",', '","') + ']'
print (ss)

[{"apple":"34253453","oranges":"Sweet","x":"COOL"},
 {"apple":"34222453","oranges":"Dry","x":"WARM"},
 {"apple":"31113453","oranges":"Bitter","x":"HOT"},
 {"apple":"38883453","oranges":"Sweet","x":"COOL"}]

df = pd.DataFrame(ast.literal_eval(ss))
print (df)
      apple oranges     x
0  34253453   Sweet  COOL
1  34222453     Dry  WARM
2  31113453  Bitter   HOT
3  38883453   Sweet  COOL

df = pd.DataFrame(pd.io.json.loads(ss))
print (df)
      apple oranges     x
0  34253453   Sweet  COOL
1  34222453     Dry  WARM
2  31113453  Bitter   HOT
3  38883453   Sweet  COOL

暂无
暂无

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

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