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