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

标签 python pandas

我有一个这种格式的字符串:

{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/

相关文章:

python - SQLALCHEMY/PANDAS - SQLAlchemy 读取列作为 Pandas to_sql 的 CLOB

python - 如何在 python 数据帧中的多个列之间执行 'OR'?

python - 如何在 Python - GEKKO 中构建和打印循环生成的优化值列表?

Python - 脚本在守护进程后不执行其余代码

python - 如何在 python 中创建长期的 websocket 连接?

python - 有没有一种方法可以在 MySQL-Python 中对每个字符串执行多个查询?

python - Pandas 数据帧 : normalize one JSON column and merge with other columns

Python:如何从数据帧中行查找数据并根据列匹配在另一个数据帧中相乘

python - 如何将一个数据框中的列添加到另一个数据框中?

Python字典指针和引用指针?