python - Pandas groupby 计算天数
问题描述
假设我有以下数据框:
df = pd.DataFrame({'c': ['abc', 'def', 'wyx', 'abc', 'wyx'], 'begin_date': ['2020-01-01', '2000-12-23', '2003-07-07', '2005-03-02', '2004-01-01'], 'end_date': ['2020-01-31', '2001-02-02', '2004-03-02', '2005-04-01', '2004-07-04']})
df
c begin_date end_date
abc 2020-01-01 2020-01-31
def 2000-12-23 2001-02-02
wyx 2003-07-07 2004-03-02
abc 2005-03-02 2005-04-01
wyx 2004-01-01 2004-07-04
我想按 c 分组并计算该 c 的一行之间的唯一天数begin_date
,end_date
我的最终数据框将是:
end = pd.DataFrame({'c': ['abc', 'def', 'wyx'], 'count': [30, 41, 363]})
end
c count
abc 30
def 41
wyx 363
解决方案
您应该做的第一件事是转换为日期时间类型,然后您可以减去和分组:
s = (pd.to_datetime(df.end_date) - pd.to_datetime(df.begin_date)).dt.days
s.groupby(df['c']).sum()
更新:要删除重复的天数,我们可以重新采样:
df['begin_date'] = pd.to_datetime(df['begin_date'])
df['end_date'] = pd.to_datetime(df['end_date'])
(pd.concat(pd.DataFrame({
'c':x['c'],
'count':pd.date_range(x.begin_date, x.end_date)
}) for _,x in df.iterrows())
.drop_duplicates()
.groupby('c').size()
.reset_index(name='count')
)
输出:
c count
0 abc 62
1 def 42
2 wyx 364
推荐阅读
- android - 为什么 Configuration.UI_MODE_NIGHT_YES 会自动设置
- c# - 如果按下键并且音符不在盒子上,则 Unity 节奏游戏出现问题,然后算作未命中
- python - python:ValueError:太多值无法从excell中解压(预期2)数据
- python - 根据其他列中的值查询熊猫数据框的值的更快方法
- php - 无法从提交按钮导出 csv 文件
- sql - 在学生表中查找缺失值
- pine-script - 带有长短信号标签的策略计数器
- arrays - 将字符写入 char 字符串,添加了字符,但它不存在 (C)
- saga - Saga Orchestrator 是否应该存储已完成的事务状态和数据?
- c++ - 用户定义的类型特征给出了意外的错误类型