pandas.core.groupby.SeriesGroupBy.cumcount#

SeriesGroupBy.cumcount(ascending=True)[源代码]#

为组中的每个项从 0 编号到该组的长度减 1。

这基本上等同于

self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))
Parameters:
ascendingbool, default True

如果为 False,则反向编号,从组的长度减 1 到 0。

Returns:
Series

每个组中每个元素的序列号。

参见

ngroup

对组本身进行编号。

Examples

>>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],
...                   columns=['A'])
>>> df
   A
0  a
1  a
2  a
3  b
4  b
5  a
>>> df.groupby('A').cumcount()
0    0
1    1
2    2
3    0
4    1
5    3
dtype: int64
>>> df.groupby('A').cumcount(ascending=False)
0    3
1    2
2    1
3    1
4    0
5    0
dtype: int64