【问题标题】:Insert Pandas Timestamp into Mongodb将 Pandas 时间戳插入 Mongodb
【发布时间】:2016-08-22 11:41:32
【问题描述】:

我正在尝试使用 PyMongo 将 Pandas DataFrame 插入 Mongodb。

df.head()

因为如果 Pandas DataFrame 是 DatetimeIndex 的索引,将 DataFrame 转换为 dict 并将其插入到 Mongodb:

db.testCollection.insert( df.T.to_dict() )

导致错误:

InvalidDocument: documents must have only string keys, key was Timestamp('2016-04-07 09:30:00')

我们如何将DatetimeIndex 转换为可以插入到 Mongodb 中的其他东西,然后在从 Mongodb 读取时仍然能够转换回 DatetimeIndex?

【问题讨论】:

    标签: python mongodb pandas pymongo


    【解决方案1】:

    一种解决方案是在尝试存储到 MongoDB 之前将索引转换为 str,如下所示:

    >> df.index = df.index.astype(str)
    >> db.testCollection.insert(df.T.to_dict())
    

    稍后再次从 db 中读取数据时,您可以将索引转为时间戳:

    >> df.index = pd.to_datetime(df.index)
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2021-12-31
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多