我有一个包含以下内容的 mongodb 集合:
[{'price': 0.74881,,
'date': '20160601 00:00:00.134',
'instrument': 'EUR/GBP'},
{'price': 0.76881,
'date': '20160601 00:00:00.135',
'instrument': 'EUR/GBP'},
{'price': 0.78881,
'date': '20160601 00:00:00.300',
'instrument': 'EUR/GBP'},
{'price': 1.76881,
'date': '20160601 00:00:00.302',
'instrument': 'EUR/GBP'},
我如何更新每条记录,使其包含出价增加/减少的百分比,并询问以前的记录?真实记录包含数百万个条目,因此 pandas 不适合。
在输出中,每条记录都应包含一个名为 price_change_to_pervious_item 的附加字段
最佳答案
您似乎想以成对方式处理您的记录。 此函数来自 itertools documentation本身。
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
一旦你有了它,假设你的数据已经排序
results = []
for d1, d2 in pairwise(data):
if not result:
d1['price_change_to_pervious_item'] = 0.0
results.append(d1)
delta = d2['price'] - d1['price']
d2['price_change_to_pervious_item'] = delta
results.append(d2)
这没有经过测试,但您已经了解了大概的想法。 Pairwise 允许您以 (d1,d2), (d2,d3) 的方式处理行。
关于python - Mongodb 与上一个条目的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38284079/