Pandas number rows within group in increasing order

后端 未结 2 445
不思量自难忘°
不思量自难忘° 2020-11-28 07:06

Given the following data frame:

import pandas as pd
import numpy as np
df=pd.DataFrame({\'A\':[\'A\',\'A\',\'A\',\'B\',\'B\',\'B\'],
                \'B\':[\'         


        
相关标签:
2条回答
  • 2020-11-28 07:17

    Use groupby.rank function. Here the working example.

    df = pd.DataFrame({'C1':['a', 'a', 'a', 'b', 'b'], 'C2': [1, 2, 3, 4, 5]})
    df
    
    C1 C2
    a  1
    a  2
    a  3
    b  4
    b  5
    
    df["RANK"] = df.groupby("C1")["C2"].rank(method="first", ascending=True)
    df
    
    C1 C2 RANK
    a  1  1
    a  2  2
    a  3  3
    b  4  1
    b  5  2
    
    
    0 讨论(0)
  • 2020-11-28 07:26

    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
    
    0 讨论(0)
提交回复
热议问题