Python pandas - filter rows after groupby

前端 未结 4 1963
天涯浪人
天涯浪人 2020-11-27 14:00

For example I have following table:

index,A,B
0,0,0
1,0,8
2,0,8
3,1,0
4,1,5

After grouping by A:

0:
index,A,B
         


        
4条回答
  •  -上瘾入骨i
    2020-11-27 14:41

    Here's the other example for : Filtering the rows with maximum value after groupby operation using idxmax() and .loc()

    In [465]: import pandas as pd
    
    In [466]:   df = pd.DataFrame({
                   'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2'],
                   'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4'], 
                   'value' : [3,2,5,8,10,1]     
                    })
    
    In [467]: df
    Out[467]: 
       mt   sp  value
    0  S1  MM1      3
    1  S1  MM1      2
    2  S3  MM1      5
    3  S3  MM2      8
    4  S4  MM2     10
    5  S4  MM2      1
    
    ### Here, idxmax() finds the indices of the rows with max value within groups,
    ### and .loc() filters the rows using those indices :
    In [468]: df.loc[df.groupby(["mt"])["value"].idxmax()]                                                                                                                           
    Out[468]: 
       mt   sp  value
    0  S1  MM1      3
    3  S3  MM2      8
    4  S4  MM2     10
    

提交回复
热议问题