我有一个这种格式的字符串:
{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 convert comma separated list to pandas dataframe以及 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
关于python - 如何将逗号分隔的字典字符串拆分为 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140908/