【发布时间】:2021-09-17 08:38:29
【问题描述】:
我有以下数据框,但不确定如何将其转换为有用的 Json 输出。
Name Id Qty Value
thing1 123 10 12.5
thing2 456 20 15.4
thing3 789 40 84.2
我目前正在使用to_json(),但我有点不确定如何使用它来生成以下 json 架构。我想要
{"Name":"thing1"
"Id":123,
"Quantity":10,
"Value":12.5
},
{"Name":"thing2"
"Id":456,
"Quantity":20,
"Value":15.4
},
{"Name":"thing3"
"Id":789,
"Quantity":40,
"Value":84.2
},
我现在可以使用的解决方案
out=df.reset_index().to_json(orient='record')
【问题讨论】:
-
你可以试试:
df.to_json(orient='records') -
也许你的
Name和id是索引?试试:df.reset_index().to_json(orient='records')? -
df.to_dict("records") -
谢谢大家! reset_index 成功了。
-
@RobRaymond
to_dict()和to_json()的输出略有不同。to_dict()给出单引号输出,而to_json()给出双引号,这似乎更符合 OP 的要求。