【发布时间】:2021-09-28 09:55:54
【问题描述】:
Python 3.9,Win 10 上的 Pandas 1.3.0
嗨,
我有一个 DataFrame (df),其中两列包含 Unix 时间戳(第 0 列和第 6 列,“开放时间”和“关闭时间”)。
open time open high ... volume close time number of trades 0 1609459200000 736.42 739.00 ... 27932.69884 1609462799999 22671 1 1609462800000 734.08 749.00 ... 52336.18779 1609466399999 41712
我使用以下代码将这些重新格式化为 dtype = datetime64:
df.iloc[:,0] = pd.to_datetime(df['open time'], unit='ms')
df.iloc[:,6] = pd.to_datetime(df['close time'], unit='ms')
结果就是我想要的,日期时间精确到毫秒,用 df.head()
查看open time open ... close time number of trades 0 2021-01-01 00:00:00 736.42 ... 2021-01-01 00:59:59.999 22671 1 2021-01-01 01:00:00 734.08 ... 2021-01-01 01:59:59.999 41712
但是,当我将其写入 json 文件时,不会保存更改。
df.to_json("ETHUSDT_out_hist1.json", orient="records", indent=2)
生成的 .json 文件内容 - Unix 时间戳仍然存在:
{"open time":1609459200000,
"open":736.42,
// 1, 2, skip a few
"close time":1609462799999,
"number of trades":22671}
我怀疑我是通过应用 to_datetime 方法而不是更改原始 df 对象来创建副本的。
我的问题是,如何更改原始对象/DataFrame,以便我的更改将保存到 json 文件中? to_datetime 没有就地参数,我似乎无法弄清楚如何将更改分配回原始 df。 拖网几个小时,Pandas 文档和其他论坛也没有找到可行的解决方案。
提前致谢
【问题讨论】:
标签: python json python-3.x pandas