Python pandas - filter rows after groupby

前端 未结 4 1962
天涯浪人
天涯浪人 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条回答
  •  [愿得一人]
    2020-11-27 14:24

    You just need to use apply on the groupby object. I modified your example data to make this a little more clear:

    import pandas
    from io import StringIO
    
    csv = StringIO("""index,A,B
    0,1,0.0
    1,1,3.0
    2,1,6.0
    3,2,0.0
    4,2,5.0
    5,2,7.0""")
    
    df = pandas.read_csv(csv, index_col='index')
    groups = df.groupby(by=['A'])
    print(groups.apply(lambda g: g[g['B'] == g['B'].max()]))
    

    Which prints:

             A  B
    A index      
    1 2      1  6
    2 4      2  7
    

提交回复
热议问题