python - 从 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 万行。我想避免将其减少到仅年/月/日,它不需要降至秒,但最接近小时的价格就足够了。
解决方案
推荐阅读
- java - 解析三重嵌套 JSON 的最简单方法是什么?
- postman - 试图在工作区中获取两个 postman.setNextRequest(未链接)或两个操作
- python - 如何从我的数据集中提取数字并制作一个数组?
- javascript - 如何按某个属性排序进行映射
- mysql - 创建新的 MySQL 用户:主机匹配是什么意思?
- python - 从 imshow 获取数组而不绘制它
- javascript - '&' 如何与奇数和偶数相关联?在 JS 中
- c++ - 选择错误时如何允许用户再次输入
- .net - 无法使用 AWSLogDriver 发送日志
- c++ - 为什么可以访问在 for 循环中创建并保存到向量向量中的向量?