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

Pandas分组后每组内每两行分配组序号的实现问题

问题

现有如下DataFrame:

import pandas as pd

data = {
    'TileDesc': ['AA', 'AA', 'AA', 'AA', 'AA', 'BB', 'BB', 'BB', 'BB'],
    'ReportDesc': ['New Report-1', 'New Report-2', 'New Report-1', 'New Report-1', 'New Report-1',
                   'New Report-4', 'New Report-2', 'New Report-4', 'New Report-6'],
    'UrlLink': ['link-1', 'link-2', 'link-1', 'link-1', 'link-1',
                'link-4', 'link-2', 'link-4', 'link-6']
}
df = pd.DataFrame(data)

需要新增Group列,要求在每个TileDesc分组内,每连续两行使用同一组序号,每过两行序号递增,期望结果如下:

TileDesc    ReportDesc UrlLink  Group
0       AA  New Report-1  link-1      1
1       AA  New Report-2  link-2      1
2       AA  New Report-1  link-1      2
3       AA  New Report-1  link-1      2
4       AA  New Report-1  link-1      3
5       BB  New Report-4  link-4      1
6       BB  New Report-2  link-2      1
7       BB  New Report-4  link-4      2
8       BB  New Report-6  link-6      2

尝试过两种方法但均不符合需求:

  1. 使用ngroup方法,会给同一TileDesc的所有行分配相同组号:
df['Group'] = df.groupby(['TileDesc']).ngroup()
  1. 使用全局索引计算分组,未考虑TileDesc的分组逻辑:
import math
df['Index'] = df.index + 1
df['Group'] = df['Index'].apply(lambda x : math.ceil(x/4))

请问正确的实现方式是什么?

解决方案

可以通过groupby按TileDesc分组后,利用cumcount()获取每个分组内的行索引(从0开始),再通过向上取整计算分组序号:

import pandas as pd
import math

# 构造原始DataFrame
data = {
    'TileDesc': ['AA', 'AA', 'AA', 'AA', 'AA', 'BB', 'BB', 'BB', 'BB'],
    'ReportDesc': ['New Report-1', 'New Report-2', 'New Report-1', 'New Report-1', 'New Report-1',
                   'New Report-4', 'New Report-2', 'New Report-4', 'New Report-6'],
    'UrlLink': ['link-1', 'link-2', 'link-1', 'link-1', 'link-1',
                'link-4', 'link-2', 'link-4', 'link-6']
}
df = pd.DataFrame(data)

# 新增Group列
df['Group'] = df.groupby('TileDesc').cumcount().apply(lambda x: math.ceil((x + 1) / 2))

print(df)

代码解释

  • df.groupby('TileDesc').cumcount():为每个TileDesc分组内的行生成从0开始的连续序号,比如AA分组的行序号是0、1、2、3、4,BB分组是0、1、2、3。
  • lambda x: math.ceil((x + 1) / 2):将序号+1后除以2并向上取整,实现每两行一组的效果:
    • 0+1=1 → ceil(1/2)=1
    • 1+1=2 → ceil(2/2)=1
    • 2+1=3 → ceil(3/2)=2
    • 以此类推,完美匹配需求的分组逻辑。

输出结果

TileDesc    ReportDesc UrlLink  Group
0       AA  New Report-1  link-1      1
1       AA  New Report-2  link-2      1
2       AA  New Report-1  link-1      2
3       AA  New Report-1  link-1      2
4       AA  New Report-1  link-1      3
5       BB  New Report-4  link-4      1
6       BB  New Report-2  link-2      1
7       BB  New Report-4  link-4      2
8       BB  New Report-6  link-6      2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:20:41