json - 序列化和反序列化 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
解决方案
一种解决方法是在转储之前转换PeriodIndex
为常规并在加载后将Index
其转换回:PeriodIndex
regular_idx = period_idx.astype(str)
# then dump
# after load
period_idx = pd.to_datetime(regular_idx).to_period()
推荐阅读
- php - 为什么在 laravel eloquent 中使用 load() 时 $this 为空?
- vue.js - 如何在 VueJS 中合并 2 个第三方组件
- asp.net-mvc-4 - ASP.Net MVC 控制器构造函数显示错误 System.Web.Mvc.Controller.Session.get 返回 null
- python - 如何在pyqt中实现QLineEdit和QLineEdit之间没有间隙
- java - 使用 G1 Collector,可以将一个数组对象分配给不同的对象吗?
- reactjs - CRA 中的 setupProxy 文件使反应脚本启动失败,命令失败,退出代码 1 错误
- flutter - Flutter-webrtc 包
- javascript - 加载 jQuery 两次 HTML
- swift - iOS 打开 PDF 文件中的可点击链接
- javascript - 此导航器缺少导航道具。在 react-navigation v3 和 v4 中,您必须直接设置您的应用容器