组内的 pandas 编号行按升序排列 [英] Pandas number rows within group in increasing order

查看:136
本文介绍了组内的 pandas 编号行按升序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数据框:

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

我想创建列'C',这样对A和B列中每个组中的行进行编号,如下所示:

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!

推荐答案

使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆