首页 > 解决方案 > 从 MongoDB 集合中查找大型 DataFrame 中日期的匹配项并使用结果创建新列

问题描述

试图找到一种方法来最好地优化我的熊猫数据框中每一行的 collection.find() 。

假设我有一个交易数据的 DF。我还有一个数据库,其中包含每个日期的股票价格。我如何使用数据框中的日期来最有效地从 mongoDB 中找到相应的价格

就像是 df = pd.DataFrame(columns=['blockTimestamp','feature1', 'feature2']

我试图通过将它缩小到一个范围来优化它,并将它与一个合并绑定在一起。

start_date = df['blockTimestamp'].min()
end_date = df['blockTimestamp'].max()

print('Retrieving historical price data from MongoDB')
results = []
for timestamp in historical.find({'date':{'$gte':start_date, '$lte':end_date}}, {'date':1, 'open':1 }):
    pairs = (timestamp.get('date'), timestamp.get('open'))
    results.append(pairs)
        
df1 = pd.DataFrame(results, columns=['blockTimestamp', 'usdPrice'])

df = df.merge(df1, on='blockTimestamp', how='left')

这并没有节省尽可能多的时间,任何提示和技巧。让我们想象一下我试图填充 100 万行。我想避免将其减少到仅年/月/日,它不需要降至秒,但最接近小时的价格就足够了。

标签: pythonpandasmongodb

解决方案


推荐阅读