python - 另一个DataFrame的pandas dataframe求和日期范围

标签 python pandas dataframe

我有两个数据框。我想在第 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

您可以使用 numpyouter 功能非常有效地实现这一点比较,因为 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)

并使用 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/

相关文章:

python - 使用机器学习算法从python中的两个列表中找到最短点

python - 无法从 'detail_route' 导入名称 'rest_framework.decorators'

python - 在管理命令中保存 Django 数据库中的图像

python - Pandas 中的外部连接三个数据帧不起作用

python - 根据列的多个条件将数据帧拆分为 block

python - 我如何自动化我用 python 编写的爬虫程序每月运行一次?

python - 将值从 1 列映射到另一列(如果按 id 分组时存在)

python - 如何计算基于另一列的两列的唯一值? (每个身份证)

python - 将最后 N 个重复项保留在 pandas 中

python - 如何计算Python DataFrame中非连续行之间的差异?