我有两个数据框。我想在第 2 个中为第一个数据名中的每条记录求和一个“数量”列。
所以对于每个
df1.Date = sum(df2.amount WHERE df1.Date <= df2.Date AND df1.yearAgo >= df2.Date)
df1 = pd.DataFrame({'Date':['2018-10-31','2018-10-30','2018-10-29','2018-10-28'],'yearAgo':['2017-10-31','2017-10-30','2017-10-29','2017-10-28']})
df2 = pd.DataFrame({'Date':['2018-10-30','2018-7-30','2018-4-30','2018-1-30','2017-10-30'],'amount':[1.0,1.0,1.0,1.0,0.75]})
期望的结果:
df1.Date yearToDateTotalAmount
2018-10-31 3.0
2018-10-30 4.75
2018-10-29 3.75
2018-10-28 3.75
最佳答案
IIUC,您预期的输出应该在第一行有 4
。
您可以使用 numpy
的 outer
功能非常有效地实现这一点比较,因为 less_equal
和 greater_equal
是 ufunc
。
注意
>>> np.greater_equal.outer(df1.Date, df2.Date)
array([[ True, True, True, True, True],
[ True, True, True, True, True],
[False, True, True, True, True],
[False, True, True, True, True]])
所以你可以通过以下方式获得你的面具
mask = np.greater_equal.outer(df1.Date, df2.Date) &
np.less_equal.outer(df1.yearAgo, df2.Date)
并使用 outer multiplication
+ 沿 axis=1
>>> np.sum(np.multiply(mask, df2.amount.values), axis=1)
Out[49]:
array([4. , 4.75, 3.75, 3.75])
最后直接赋值回去
>>> df1['yearToDateTotalAmount'] = np.sum(np.multiply(mask, df2.amount.values), axis=1)
Date yearAgo yearToDateTotalAmount
0 2018-10-31 2017-10-31 4.00
1 2018-10-30 2017-10-30 4.75
2 2018-10-29 2017-10-29 3.75
3 2018-10-28 2017-10-28 3.75
关于python - 另一个DataFrame的pandas dataframe求和日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53269061/