pandas.core.groupby.DataFrameGroupBy.cumcount #
- DataFrameGroupBy。cumcount (升序= True ) [来源] #
从 0 到该组的长度 - 1 对每组中的每个项目进行编号。
本质上这相当于
self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))
- 参数:
- 升序布尔值,默认 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