我有一个通用的 pandas TimeSeries,我想将其存储在 MongoDB 中。对象 ts 看起来像这样:
>ts
2013-01-01 00:00:00 456.852985
2013-01-01 01:00:00 656.015532
2013-01-01 02:00:00 893.159043
...
2013-12-31 21:00:00 1116.526471
2013-12-31 22:00:00 1124.903600
2013-12-31 23:00:00 1065.315890
Freq: H, Length: 8760, dtype: float64
我想将其转换为一组 JSON 文档,其中一个文档是一行,以将其存储在 MongoDB 中。像这样:
[{"index": 2013-01-01 00:00:00, "col1": 456.852985},
{"index": 2013-01-01 01:00:00, "col1": 656.015532},
{"index": 2013-01-01 02:00:00, "col1": 893.159043},
...
]
我一直在研究 TimeSeries.to_json() 'orient' 选项,但我看不到它们获取这种格式的方式。有没有一种在 Pandas 中执行此操作的简单方法,或者我应该寻找一种使用外部 JSON 库创建此结构的方法?
最佳答案
一种方法是使用 reset_index
使其成为一个框架,以便使用 record orient of to_json
:
In [11]: df = s.reset_index(name='col1')
In [12]: df
Out[12]:
index col1
0 2013-01-01 00:00:00 456.852985
1 2013-01-01 01:00:00 656.015532
2 2013-01-01 02:00:00 893.159043
In [13]: df.to_json(orient='records')
Out[13]: '[{"index":"2013-01-01 00:00:00","col1":456.852985},{"index":"2013-01-01 01:00:00","col1":656.015532},{"index":"2013-01-01 02:00:00","col1":893.159043}]'
关于python - Pandas TimeSeries 到 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22546841/