我正在尝试使用PyMongo将Pandas DataFrame插入Mongodb。
0
因为Pandas DataFrame的索引是df.head()
,所以将DataFrame转换为DatetimeIndex
并将其插入Mongodb:
dict
引起错误:
db.testCollection.insert( df.T.to_dict() )
我们如何将InvalidDocument: documents must have only string keys, key was Timestamp('2016-04-07 09:30:00')
转换为可插入Mongodb的其他内容,以后在从Mongodb读取时仍可以转换回DatetimeIndex?
答案 0 :(得分:2)
解决方法是在尝试存储在MongoDB之前将索引转换为str
,如下所示:
>> df.index = df.index.astype(str)
>> db.testCollection.insert(df.T.to_dict())
稍后再次从db读取数据时,您可以将索引转换为时间戳:
>> df.index = pd.to_datetime(df.index)
我希望这会有所帮助