python - sumifs 解决给定问题的 python 等价物是什么
问题描述
这是数据框
import pandas as pd
df = pd.DataFrame({'IDENTIFIER': ['A_xcxcxc', 'BA_bcbcbc', 'A_xcxcxc', 'A_xcxcxc', 'BA_bcbcbc', 'C_rgrg', 'BA_bcbcbc', 'D_wewerw', 'A_xcxcxc', 'A_xcxcxc'],
'income': [-30362100.0, 200000.0, -21248077.5, 150000.0, -33843389.2, 200000.0, -40229279.75, 250000.0, -22111384.6, 200000.0],
'Date' : ['03/03/2031', '22/01/2060', '04/03/2025', '22/07/2032', '08/03/2028', '22/11/2065', '05/04/2024', '22/03/2032', '15/10/2025', '22/07/2065']
})
我想汇总每个标识符的收入,但前提是它在 2030 年 1 月 1 日之前。只是为了澄清我是否使用 sumifs 在 excel 中这样做,我得到了这个
我假设可以使用 groupby 函数来完成,但不确定如何添加与日期相关的条件。
解决方案
首先过滤日期在 2030 年 1 月 1 日之前的行,然后执行 groupby 并求和:
import pandas as pd
import datetime
df = pd.DataFrame({'IDENTIFIER': ['A_xcxcxc', 'BA_bcbcbc', 'A_xcxcxc', 'A_xcxcxc', 'BA_bcbcbc', 'C_rgrg', 'BA_bcbcbc', 'D_wewerw', 'A_xcxcxc', 'A_xcxcxc'],
'income': [-30362100.0, 200000.0, -21248077.5, 150000.0, -33843389.2, 200000.0, -40229279.75, 250000.0, -22111384.6, 200000.0],
'Date' : ['03/03/2031', '22/01/2060', '04/03/2025', '22/07/2032', '08/03/2028', '22/11/2065', '05/04/2024', '22/03/2032', '15/10/2025', '22/07/2065']
})
# convert string column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# limit for the filter
limit = datetime.datetime(year=2030, month=1, day=1)
# do the operation - df.loc[df.Date < limit] is the filter
df.loc[df.Date < limit].groupby('IDENTIFIER').sum()
输出:
income
IDENTIFIER
A_xcxcxc -43359462.10
BA_bcbcbc -74072668.95
推荐阅读
- tfs - 将工作项分配给受信任域中的用户
- python - 我不断收到 BadRequestKeyError 400,我不知道为什么
- css - 使用 puppeteer 生成 PDF 时缺少内容
- python - 为什么 python 中 scipy.optimze 中的 curve_Fit 在这段代码中表现得很奇怪?
- c# - Task.Run() 阻止 .net 核心应用程序的启动
- android - 我的手机没有在 android studio 中显示
- typescript - Discord 机器人消息问题
- javascript - DataTables - 导出数据中的所有列,无论表中可见什么
- c# - 为什么我新创建的方法没有出现在引用该方法所属类的不同类中?
- python-3.x - 如何使 pylint 为存储库中的所有函数和方法强制执行文档字符串