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

Pandas如何按chapter分组创建组内顺序position_in_chapter列

实现方法

你可以直接用pandas内置的groupby.cumcount()方法实现,一行代码即可完成需求,不需要额外冗余处理:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'cluster_title': ["rabbits", "horses", "cows", "trains", "airplanes", "ships", "carrot", "potato", "tomato"],
    'chapter': [1,1,1,2,2,2,3,3,3]
})

# 核心逻辑:按chapter分组,生成组内顺序编号(cumcount默认从0开始,+1后转为从1开始计数)
df['position_in_chapter'] = df.groupby('chapter').cumcount() + 1

print(df)

运行后输出的结果完全符合你要求的格式。

补充说明

  • 上述逻辑默认保留原DataFrame中每个chapter下cluster_title的原有顺序生成编号
  • 如果你需要先按cluster_title字典序排序后再生成位置,可在分组前先执行排序操作:
df = df.sort_values(['chapter', 'cluster_title'], ignore_index=True)
df['position_in_chapter'] = df.groupby('chapter').cumcount() + 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:39:00