简体   繁体   English

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

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

I have a string in this format: 我有以下格式的字符串:

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

And looking to create a dataframe with the column labels as 'apple','oranges','x' and the values placed in their respective rows. 并希望创建一个数据框,其列标签为“ apple”,“ oranges”,“ x”,并将值放置在它们各自的行中。

I've tried to use this solution: Python convert comma separated list to pandas dataframe as well as ast.literal_eval to convert it into a list before transforming it into a dataframe but to no luck. 我尝试使用此解决方案: Python将逗号分隔的列表转换为熊猫数据框,以及将ast.literal_eval转换为列表,然后再将其转换为数据框,但没有运气。

Your string is invalid json , so necessary some replace first: 您的字符串是无效的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.

相关问题 如何将 Pandas 数据帧行转换为逗号分隔的字符串 - How to turn a pandas dataframe row into a comma separated string 如何拆分括号内用逗号分隔的字符串 - How to split string separated by a comma within the bracket 在 Pandas Dataframe 中将字符串(逗号分隔)转换为 int 列表 - Convert string (comma separated) to int list in pandas Dataframe 在熊猫数据框中以逗号分隔的字符串中的每一项添加+1 - Add +1 to each item in a comma-separated string in pandas dataframe 正则表达式用 pandas dataframe 中的总和替换用逗号分隔的字符串 - Regular expression to replace string separated by comma with thier sum in pandas dataframe 将具有键值形式的逗号分隔字符串转换为 pandas Dataframe - Converting comma separated string with key-value form into pandas Dataframe 带有逗号分隔字符串条目的熊猫数据框,更改为唯一的逗号分隔条目 - pandas dataframe with comma separated string entries, change to unique comma separated entries 熊猫-逗号分隔行中的每个字符串在数据帧中出现的频率 - Pandas - how often each string in comma separated rows is present within dataframe 如何在Pandas列中拆分逗号分隔的单词列表? - How can I split a list of comma separated words in a Pandas column? 将字典列表转换为逗号分隔的字符串 python - Convert list of Dictionaries to comma separated string python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM