gpt4 book ai didi

python - 如何将 pandas DataFrame 的日期时间索引作为 isoDate 类型的字段插入 mongodb

转载 作者:行者123 更新时间:2023-12-01 04:18:42 32 4
gpt4 key购买 nike

我有一个类型为 pandas.core.frame.DataFrame 的数据框喜欢:

              open  high  close   low    volume     amount
date
2015-11-27 8.10 8.16 7.35 7.34 37877648 294274400
2015-11-26 8.03 8.44 8.16 8.00 45933600 378897088
2015-11-25 7.95 8.03 7.99 7.89 21255886 169172176
2015-11-24 7.95 8.18 8.04 7.85 24808112 199120256
2015-11-23 8.24 8.29 7.95 7.93 29176848 236019264

df.index

DatetimeIndex(['2015-11-27', '2015-11-26', '2015-11-25', '2015-11-24',
'2015-11-23', '2015-11-20', '2015-11-19', '2015-11-18',
'2015-11-17', '2015-11-16',
...
'2014-12-12', '2014-12-11', '2014-12-10', '2014-12-09',
'2014-12-08', '2014-12-05', '2014-12-04', '2014-12-03',
'2014-12-02', '2014-12-01'],
dtype='datetime64[ns]', name=u'date', length=193, freq=None)

如何将 df 插入到 mongodb 中,其中包含 isoDate 格式的 date.index 字段,而不是 datatime64[ns]/timestamps? .

最佳答案

困扰了很久,终于找到办法了。这取决于我们插入 mongod 的方式。我以前是这样插入mongod的:

records = json.loads(DataFrame.T.to_json()).values()
collection.insert_many(records)

我们需要了解这种方法会将 DataFrame 时间转换为 datatime64[ns]/timestamps。

print records[0]
{u'dtime': 1407076151000L,u'olddtime': u'2014/8/3 14:29:11'}

我们可以看到它保存的时间为numberlong,DateTime为string。所以我们需要更改记录:

for row in records:
row['olddtime'] = datetime.datetime.strptime(row['olddtime'], "%Y/%m/%d %H:%M:%S")

然后我们打印它:

{u'olddtime': datetime.datetime(2014, 8, 3, 14, 29, 11), u'dtime': 1407076151000L}

最后我们这样做:

collection.insert_many(records)

没关系!

关于python - 如何将 pandas DataFrame 的日期时间索引作为 isoDate 类型的字段插入 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993946/

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