gpt4 book ai didi

python - pandas Dataframe 到 JSON 字典列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:37:21 34 4
gpt4 key购买 nike

这是样本数据集

datetime  2017-12-24  2017-12-31                             
a 1.5 0.5
b 0.0 1.5
c 1.5 0.0

我正在使用 to_json 将其转换为 json,我得到了这个输出

{"2017-12-24":{"a":1.5,"b":0.0,"c":1.5},"2017-12-31":{"a":0.5,"b":1.5,"c":0.0}}

我想做的是让 json 得到一个像这样的字典列表

[{"datetime":"2017-12-24","a":1.5,"b":0.0,"c":1.5},{"datetime":"2017-12-31", "a":0.5,"b":1.5,"c":0.0}]

我的代码在这里

df = pd.DataFrame({'2017-12-24': [1.5, 0.0, 1.5], '2017-12-31': [0.5, 1.5, 0.0]}, index=['a', 'b', 'c'])
df.columns.name='datetime'
print(df.to_json())

最佳答案

转置reset_indexto_json

i = df.T.reset_index()
i

datetime a b c
0 2017-12-24 1.5 0.0 1.5
1 2017-12-31 0.5 1.5 0.0

i.to_json()
'[{"datetime":"2017-12-24","a":1.5,"b":0.0,"c":1.5},{"datetime":"2017-12-31","a":0.5,"b":1.5,"c":0.0}]'

入栈 + 出栈

(df.stack()
.unstack(0)
.reset_index()
.to_json(orient='records'))

'[{"datetime":"2017-12-24","a":1.5,"b":0.0,"c":1.5},{"datetime":"2017-12-31","a":0.5,"b":1.5,"c":0.0}]'

关于python - pandas Dataframe 到 JSON 字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48012197/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com