gpt4 book ai didi

python - Pandas TimeSeries 到 MongoDB

转载 作者:可可西里 更新时间:2023-11-01 09:44:39 29 4
gpt4 key购买 nike

我有一个通用的 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/

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