gpt4 book ai didi

python - json 在重新采样 pandas 后没有列名

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:54 25 4
gpt4 key购买 nike

在对重采样数据使用 to_json 时如何获取列名?

amount = df['amount'].resample('M').last()
amount = amount.to_json()

我得到的输出:

{"1501459200000":1.79,"1504137600000":88.80}

我想要的输出:

[{"time":"1501459200000","amount":1.79},{"time":"1504137600000","amount":88.80}]

最佳答案

您可以在 to_json 中使用参数 orient='records' , 但如果只需要 dates 添加 strftime , 用于重命名索引 rename_axisreset_index对于 index 中的列:

df = pd.DataFrame({'amount': np.random.rand(10)}, 
index=pd.date_range('2018-01-01', periods=10, freq='20D'))

print (df)
amount
2018-01-01 0.015710
2018-01-21 0.128403
2018-02-10 0.508626
2018-03-02 0.884921
2018-03-22 0.820198
2018-04-11 0.574304
2018-05-01 0.961553
2018-05-21 0.352586
2018-06-10 0.965337
2018-06-30 0.112810

amount = df['amount'].resample('M').last().rename_axis('time').reset_index()
amount['time'] = amount['time'].dt.strftime('%Y-%m-%d')
amount = amount.to_json(orient='records')
print (amount)

[{"time":"2018-01-31","amount":0.1284033196},
{"time":"2018-02-28","amount":0.5086261293},
{"time":"2018-03-31","amount":0.8201977996},
{"time":"2018-04-30","amount":0.5743039198},
{"time":"2018-05-31","amount":0.352586249},
{"time":"2018-06-30","amount":0.1128097924}]

关于python - json 在重新采样 pandas 后没有列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906809/

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