Skip to main content
 首页 » 编程设计

python之如何在数据框的多列上应用累积计数

2025年05月04日19Renyi-Fan

数据框

    a   b   c 
0   0   1   1 
1   0   1   1 
2   0   0   1 
3   0   0   1 
4   1   1   0 
5   1   1   1 
6   1   1   1 
7   0   0   1 

我正在尝试在数据框的多列上应用累积计数 cumcount,我尝试通过对每一列进行分组来应用累积计数。有什么简单的方法可以达到预期的输出

我试过这段代码,但它不起作用

li =[] 
for column in df.columns: 
    li.append(df.groupby(column)[column].cumcount()) 
pd.concat(li,axis=1) 

预期输出

    a   b   c 
0   1   1   1 
1   1   2   2 
2   1   1   3 
3   1   1   4 
4   1   1   1 
5   2   2   1 
6   3   3   2 
7   1   1   3 

请您参考如下方法:

通过与移位值进行比较来创建连续的组,并为每一列应用 cumcount,最后通过 bool 掩码设置 1:

df = (df.ne(df.shift()).cumsum() 
       .apply(lambda x: df.groupby(x).cumcount() + 1) 
       .mask(df == 0, 1)) 
print (df) 
   a  b  c 
0  1  1  1 
1  1  2  2 
2  1  1  3 
3  1  1  4 
4  1  1  1 
5  2  2  1 
6  3  3  2 
7  1  1  3 

如果性能很重要,另一种解决方案 - 仅计算 1 值并通过 np.where 掩码最后设置 1:

a = df == 1 
b = a.cumsum() 
arr = np.where(a, b-b.mask(a).ffill().fillna(0).astype(int), 1) 
 
df = pd.DataFrame(arr, index=df.index, columns=df.columns) 
print (df) 
   a  b  c 
0  1  1  1 
1  1  2  2 
2  1  1  3 
3  1  1  4 
4  1  1  1 
5  2  2  1 
6  3  3  2 
7  1  1  3