gpt4 book ai didi

json - 序列化和反序列化 pandas periodIndex 系列

转载 作者:行者123 更新时间:2023-12-04 19:43:29 25 4
gpt4 key购买 nike

Pandas Series.to_json()函数在使用 PeriodIndex 时创建不可读的 JSON。
发生的错误是:json.decoder.JSONDecodeError: Expecting ':' delimiter: line 1 column 5 (char 4)
我试过改变方向,但是在所有这些序列化和反序列化的组合中,索引都丢失了。

idx = pd.PeriodIndex(['2019', '2020'], freq='A')
series = pd.Series([1, 2], index=idx)
json_series = series.to_json() # This is a demo - in reality I'm storing this in a database, but this code throws the same error
value = json.loads(json_series)

A link to the pandas to_json docs
A link to the python json lib docs

我不使用 json.dumps 的原因是 pandas 系列对象不可序列化。

Python 3.7.3 Pandas 0.24.2

最佳答案

一种解决方法是转换 PeriodIndex定期Index在转储之前将其转换回 PeriodIndex加载后:

regular_idx = period_idx.astype(str)
# then dump

# after load
period_idx = pd.to_datetime(regular_idx).to_period()

关于json - 序列化和反序列化 pandas periodIndex 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442226/

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