将Pandas时间序列导入MongoDB
我有一个普通的 pandas 时间序列(TimeSeries),我想把它存储到 MongoDB 里。这个时间序列的样子是这样的:
>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 库来创建这个结构呢?
2 个回答
0
每个文档用一行来存储会非常不划算,既浪费空间又影响查询速度。
如果你在数据结构上有一些灵活性,我们开源了一个库,可以方便地将pandas(还有其他数字数据)存储到MongoDB中:
2
一种方法是使用 reset_index
把它变成一个框架,这样就可以使用 记录导向的 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}]'