Access last elements of inner multiindex level in pandas dataframe

后端 未结 1 957
无人及你
无人及你 2021-02-14 04:59

In a multi index pandas dataframe I want to access the last element of the second index for all values of the first index. The number of levels in

相关标签:
1条回答
  • 2021-02-14 05:53

    Use groupby with tail:

    print (df.groupby(level='first').tail(1))
                         A         B         C
    first second                              
    bar   two     0.053054 -0.555819  0.589998
    baz   one    -0.868676  1.293633  1.339474
    foo   three   0.407454  0.738872  1.811894
    qux   one    -0.346014 -1.491270  0.446772
    

    because last lost level second:

    print (df.groupby(level='first').last())         
                  A         B         C
    first                              
    bar    0.053054 -0.555819  0.589998
    baz   -0.868676  1.293633  1.339474
    foo    0.407454  0.738872  1.811894
    qux   -0.346014 -1.491270  0.446772
    
    0 讨论(0)
提交回复
热议问题