【问题标题】:Pandas + PyMongo: Write DataFrame to MongoDBPandas + PyMongo:将 DataFrame 写入 MongoDB
【发布时间】:2019-07-11 23:01:33
【问题描述】:

我想将 pandas DataFrame 插入 MongoDB。但是,当我这样做时,timestamp 列(这是数据框的 index_coloumn)不会插入 MongoDB。

下面是我重现问题的伪代码:

from datetime import datetime

import pandas as pd
from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.ticks
collection = db.STOCK
collection_ohlc = db.STOCK_ohlc

# Read per second ticks data from Mongo into a dataframe
results = collection.find(
    {'timestamp': {'$gte': '2019-01-24T09:15:00', '$lte': '2019-01-24T09:19:59'}})
df = pd.DataFrame(list(results))

# Convert per second ticks data into 1 Minute OHLC Candle
df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
df.set_index('timestamp', inplace=True)
ohlc_data = df['ltp'].resample('5min').ohlc()

# Print OHLC candle dataframe
print(ohlc_data)

# Write  the OHLC candle back to Mongo into a new collection STOCK_ohlc
collection_ohlc.insert_many(ohlc_data.to_dict('records'))

这是上面print(ohlc_data)语句的输出:

                       open   high    low   close
timestamp
2019-01-24 09:15:00  286.55  286.7  285.5  285.65

现在代码运行良好,ohlc 值已插入 MongoDB。但是,缺少timestamp 列。

下面是MongoShell,它列出了上面插入的记录:

> db.STOCK_ohlc.find()
{ "_id" : ObjectId("5c6abc6f4994a1bc8c3c08fd"), "open" : 286.55, "high" : 286.7, "low" : 285.5, "close" : 285.65 }
>

如我们所见,上面插入的记录中缺少时间戳。如果缺少时间戳,这将毫无用处。

我尝试了pandas.DataFrame.to_dict 中提到的各种orient,但它们似乎都没有插入MongoDB。插入数据的唯一orientrecords,但随后省略了timestamp

任何指针都会有很大帮助。

更新: 这是print(ohlc_data.to_dict('records'))的输出

[{'open': 286.55, 'high': 286.7, 'low': 285.5, 'close': 285.65}]

【问题讨论】:

  • 你能打印ohlc_data.to_dict('records')吗?看来问题是您的行键类型为timestamp 而Mongo 需要字符串键。不知何故,它被省略了。试试这个解决方案:https://stackoverflow.com/a/36909509/3710490
  • @Valijon,更新了帖子。

标签: python mongodb pandas dataframe pymongo


【解决方案1】:

当您尝试将pd.DataFrame 转换为dict 时,默认情况下to_dict(.) 会跳过索引并仅转换列。

解决方案是在使用to_dict()之前将索引设置为列:

df.reset_index(level=0, inplace=True)
collection.insert_many(df.to_dict('records'))

这是df.to_dict('records')的输出:

[{'timestamp': Timestamp('2019-01-24 09:15:00'), 'open': 286.55, 'high': 286.7, 'low': 285.5, 'close': 285.65}]

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 2017-01-29
    • 2017-12-22
    • 2013-05-31
    • 2019-07-06
    • 2020-06-12
    • 1970-01-01
    相关资源
    最近更新 更多