python - 计算一个计数器在 groupby 中递增的次数
问题描述
我有一个熊猫数据框,如下所示:
df = pd.DataFrame(data={'id':[1234, 1234, 1234, 1234, 1234], 'year':['2017', '2017', '2018', '2018', '2018'], 'count_to_today':[1, 2, 3, 3, 4})
count_to_today
我需要计算每年每年累计发生多少次id
。IE
counts = pd.DataFrame(data={'id':[1234, 1234, 1234, 1234, 1234], 'year':['2017', '2017', '2018', '2018', '2018'], 'count_to_today':[1, 2, 1, 1, 2]})
即我从一开始就有一个运行计数,我想计算它每年累积增加的次数。
我对如何做到这一点有点困惑。我知道我需要分组id
,year
但我不知道如何获得.count()
或.value_counts()
给我每年的计数。
解决方案
与您之前的问题类似,但请cumsum
改用:
df.count_to_today.diff().ne(0).groupby([df.id, df.year]).cumsum()
0 1.0
1 2.0
2 1.0
3 1.0
4 2.0
Name: count_to_today, dtype: float64
df['count_to_today'] = (
df.count_to_today.diff().ne(0).groupby([df.id, df.year]).cumsum().astype(int))
df
id year count_to_today
0 1234 2017 1
1 1234 2017 2
2 1234 2018 1
3 1234 2018 1
4 1234 2018 2
推荐阅读
- php - 在 URL 重写规则中隐藏(删除)文件夹名称不起作用
- android - 我无法在 Android Studio 中执行测试
- python - 如何从熊猫数据框中递归提取值?
- matlab - 如何用matlab函数求解高阶边界条件微分方程
- google-chrome-extension - Chrome 扩展正在存储未定义的值
- python - 从 DataFrame 中获取可用的最新记录
- python - 下载图片
- javascript - 调试器自动断开
- python - 使用 Python Numpy 和 Matplotlib 模块进行健身跟踪。从指定文件夹获取最新数据并将它们存储在 numpy 数组中
- td-engine - 插入数据时有什么方法可以限制 TDengine 只使用 TCP 吗?