如何根据ID计算同一组内的计数

San*_*apa 1 python pandas

我的数据帧看起来像:

df = pd.DataFrame({"ID":['A','B','A','A','B','B','C','D','D','C'], 
                   'count':[1,1,2,2,2,2,1,1,1,2]})
print(df)
  ID  count
0  A      1
1  B      1
2  A      2
3  A      2
4  B      2
5  B      2
6  C      1
7  D      1
8  D      1
9  C      2
Run Code Online (Sandbox Code Playgroud)

我将只有ID列,我想计算count列。逻辑是我想累积计算ID. 如果它立即重复,就像index 2 & 3它们都应该得到相同的计数。我怎样才能做到这一点?

我的尝试没有给出准确的结果:

df['x'] = df['ID'].eq(df['ID'].shift(-1)).astype(int)
df.groupby('ID')['x'].transform('cumsum')+1
0    1
1    1
2    2
3    2
4    2
5    2
6    1
7    2
8    2
9    1
Name: x, dtype: int32 
Run Code Online (Sandbox Code Playgroud)

该问题与 groupby 累积计数没有直接关系,但有所不同。

WeN*_*Ben 5

我们可以做filter然后reindex回来

(df[df.ID.ne(df.ID.shift())].groupby('ID').cumcount().add(1)
                            .reindex(df.index,method='ffill'))
Out[10]: 
0    1
1    1
2    2
3    2
4    2
5    2
6    1
7    1
8    1
9    2
dtype: int64
Run Code Online (Sandbox Code Playgroud)