Pandas 按递增顺序编号组内的行数

Pandas number rows within group in increasing order(Pandas 按递增顺序编号组内的行数)

本文介绍了Pandas 按递增顺序编号组内的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Given the following data frame:

import pandas as pd
import numpy as np
df=pd.DataFrame({'A':['A','A','A','B','B','B'],
                'B':['a','a','b','a','a','a'],
                })
df

    A   B
0   A   a 
1   A   a 
2   A   b 
3   B   a 
4   B   a 
5   B   a

I'd like to create column 'C', which numbers the rows within each group in columns A and B like this:

    A   B   C
0   A   a   1
1   A   a   2
2   A   b   1
3   B   a   1
4   B   a   2
5   B   a   3

I've tried this so far:

df['C']=df.groupby(['A','B'])['B'].transform('rank')

...but it doesn't work!

解决方案

Use groupby/cumcount:

In [25]: df['C'] = df.groupby(['A','B']).cumcount()+1; df
Out[25]: 
   A  B  C
0  A  a  1
1  A  a  2
2  A  b  1
3  B  a  1
4  B  a  2
5  B  a  3

这篇关于Pandas 按递增顺序编号组内的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Pandas 按递增顺序编号组内的行数

基础教程推荐