You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按ID分组计算Usage_type累计出现次数并新增对应列

实现方案

通过生成Usage_type对应类型的布尔标识列,再按ID分组做累计求和即可实现,核心调用pandas的groupby+cumsum方法。

固定类型写法(仅包含Note、Service两类)

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'ID': [5,6,7,5,7,10],
    'Usage_type': ['Note', 'Note', 'Service', 'Note', 'Note', 'Service']
})

# 生成两类累计统计列
df['type_Note'] = df['Usage_type'].eq('Note').astype(int).groupby(df['ID']).cumsum()
df['type_Service'] = df['Usage_type'].eq('Service').astype(int).groupby(df['ID']).cumsum()

print(df)

运行后输出结果与你给出的预期完全一致。

通用动态写法(适配任意多的Usage_type类型)

如果后续Usage_type可能新增其他类型,可以用遍历的方式自动生成所有对应累计列,无需手动写死类型:

for usage_type in df['Usage_type'].unique():
    df[f'type_{usage_type}'] = df['Usage_type'].eq(usage_type).astype(int).groupby(df['ID']).cumsum()

逻辑说明

  • 先用eq()判断当前行的Usage_type是否为目标类型,转为int后符合条件的行值为1、不符合为0
  • 按ID分组后执行cumsum()做累计求和,即可得到每个ID对应类型到当前行为止的累计出现次数

内容的提问来源于stack exchange,提问作者mmkb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:54:06