给定以下数据帧:

    col_1 col_2 col_3
0     1     A     1
1     1     B     1
2     2     A     3
3     2     A     3
4     2     A     3
5     2     B     3
6     2     B     3
7     2     B     3
8     3     A     2
9     3     A     2
10    3     C     2
11    3     C     2

我需要创建一个新列,其中的行在由"col_1"和"col_2"组成的每个组内累积编号,但也在每个"col_1"组后累积编号,如下所示:

    col_1 col_2 col_3  new
0     1     A     1     1
1     1     B     1     1
2     2     A     3     2
3     2     A     3     3
4     2     A     3     4
5     2     B     3     2
6     2     B     3     3
7     2     B     3     4
8     3     A     2     5
9     3     A     2     6
10    3     C     2     5
11    3     C     2     6

我试过:

df['new'] = df.groupby(['col_1', 'col_2']).cumcount() + 1

但这并不是前一组的预期结果.

推荐答案

这是一个棘手的问题.您希望计算组内的累积计数,但对于所有后续组,您需要跟踪已增加的数量,以便知道要应用的偏移量.这可以通过max+cumsum来完成,其中cumcount组比之前的组多.这里唯一复杂的是,您需要确定之前和后续组标签之间的关系,以防后续组的标签之间没有简单的+1增量.

# Cumcount within group
s = df.groupby(['col_1', 'col_2']).cumcount()

# Determine how many cumcounts were within all previous groups of `col_1' 
to_merge = s.add(1).groupby(df['col_1']).max().cumsum().add(1).to_frame('new')

# Link group with prior group label
df1 = df[['col_1']].drop_duplicates()
df1['col_1_shift'] = df1['col_1'].shift(-1)
df1 = pd.concat([to_merge, df1.set_index('col_1')], axis=1)

# Bring the group offset over
df = df.merge(df1, left_on='col_1', right_on='col_1_shift', how='left')

# Add the group offset to the cumulative count within group.
# First group (no previous group) is NaN so fill with 1.
df['new'] = df['new'].fillna(1, downcast='infer') + s

# Clean up merging column
df = df.drop(columns='col_1_shift')

    col_1 col_2  col_3  new
0       1     A      1    1
1       1     B      1    1
2       2     A      3    2
3       2     A      3    3
4       2     A      3    4
5       2     B      3    2
6       2     B      3    3
7       2     B      3    4
8       3     A      2    5
9       3     A      2    6
10      3     C      2    5
11      3     C      2    6

Python相关问答推荐

CustomTKinter-向表单添加额外的输入字段

如何在Power Query中按名称和时间总和进行分组

使用Python C API重新启动Python解释器

"Discord机器人中缺少所需的位置参数ctx

如何使用bs 4从元素中提取文本

在编写要Excel的数据透视框架时修复标题行

Python中是否有方法从公共域检索搜索结果

如何使用没有Selenium的Python在百思买着陆页面上处理国家/地区 Select ?

根据给定日期的状态过滤查询集

Python在tuple上操作不会通过整个单词匹配

如何检测背景有噪的图像中的正方形

Pytest两个具有无限循环和await命令的Deliverc函数

将两只Pandas rame乘以指数

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

大小为M的第N位_计数(或人口计数)的公式

迭代嵌套字典的值

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

使用Python从rotowire中抓取MLB每日阵容

基于另一列的GROUP-BY聚合将列添加到Polars LazyFrame