另一个数据帧的数据帧和日期范围

2024-10-03 13:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧。我想在第二列中为第一个datafame中的每条记录加一个“amount”列。你知道吗

所以对于每个

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

Tags: and数据dataframedate记录whereamountpd
1条回答
网友
1楼 · 发布于 2024-10-03 13:22:55

IIUC,预期输出的第一行应该有4。你知道吗

使用numpy^{}比较特性可以非常有效地实现这一点,因为less_equalgreater_equalufunc

注意

>>> 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)

使用^{}+沿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

相关问题 更多 >