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

如何在Pandas中为分类索引组添加数值索引?

Pandas分组生成组内付款编号解决方案

原始数据集

clientclient caseclient payment
foo1200
foo1250
foo1225
foo2200
bar1500
bar1500

目标效果

需要为每个client+client case的分组生成连续的payment number(从1开始),最终结果如下:

clientclient caseclient paymentpayment number
foo12001
foo12502
foo12253
foo22001
bar15001
bar15002

最优解决方案

使用Pandas原生的分组+累计计数方法实现,全程为向量化操作,无需遍历行,效率拉满:

import pandas as pd

# 构造示例DataFrame(已有数据可跳过此步)
data = {
    'client': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar'],
    'client case': [1, 1, 1, 2, 1, 1],
    'client payment': [200, 250, 225, 200, 500, 500]
}
df = pd.DataFrame(data)

# 生成payment number列
df['payment number'] = df.groupby(['client', 'client case']).cumcount() + 1

代码说明

  • groupby(['client', 'client case']):按客户和案件维度完成分组
  • cumcount():为每组内的行生成从0开始的连续索引
  • +1:将索引偏移为从1开始的付款编号

运行后即可得到目标格式的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:57:17