pandas.core.groupby.DataFrameGroupBy.cumcount#

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

对每组中的每一项进行编号,从0到该组的长度-1。

从本质上讲,这相当于

self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))
参数
ascending布尔值,默认为True

如果为False,则数字反转,从组-1的长度到0。

退货
系列

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

参见

ngroup

对组本身进行编号。

示例

>>> 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