首页 > 解决方案 > 序列化和反序列化 pandas periodIndex 系列

问题描述

Series.to_json()使用 PeriodIndex 时,pandas函数会创建不可读的 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)

指向 pandas to_json 文档 的链接 指向 python json lib 文档的链接

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

Python 3.7.3 熊猫 0.24.2

标签: jsonpython-3.xpandasserialization

解决方案


一种解决方法是在转储之前转换PeriodIndex为常规并在加载后将Index其转换回:PeriodIndex

regular_idx = period_idx.astype(str)
# then dump
# after load
period_idx = pd.to_datetime(regular_idx).to_period()

推荐阅读