【问题标题】:Pandas TimeSeries into MongoDB将 Pandas TimeSeries 导入 MongoDB
【发布时间】:2014-04-28 02:48:17
【问题描述】:

我有一个通用的 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 库创建此结构的方法?

【问题讨论】:

    标签: python json mongodb pandas time-series


    【解决方案1】:

    一种方法是使用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}]'
    

    【讨论】:

    • 执行 reset_index() 以从 TimeSeries 转换为 DataFrame 看起来像是一项极其昂贵的操作。有没有办法提高效率?
    • @MonkeyButter 这可能是对 to_json 的一个很好的功能请求(对于 Series 有这个方向),这样会更有效率。
    【解决方案2】:

    在每个文档中使用一行将非常低效 - 在空间和查询性能方面。

    如果您在架构上有灵活性,我们已经开源了一个库,用于在 MongoDB 中轻松存储熊猫(和其他数字数据):

    https://github.com/manahl/arctic

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2015-04-21
      • 2013-05-25
      • 2013-04-21
      • 2017-11-02
      • 1970-01-01
      • 2020-12-13
      • 2019-07-11
      • 2017-03-10
      相关资源
      最近更新 更多