分层索引的Sum列?

时间:2017-06-21 13:48:10

标签: python loops pandas dataframe indexing

对于分层索引的列没有sum的DataFrame:

  dex1 dex2 dex3 one  two 
    H   D   A    1    2     
            B    4    5     
            C    7    8    
    I   E   A    1    1     
            B    2    2      
            C    3    3   

对于列df [' one'] index dex1,12(1 + 4 + 7),6(1 + 2 + 3),对于分层索引列的和,DataFrame应该是对于列df ['两个']索引dex1,12(1 + 4 + 7),6(1 + 2 + 3)。

到目前为止,我已经尝试过:

df.loc[dex1].sum['one']

1 个答案:

答案 0 :(得分:2)

您可以使用groupby + GroupBy.sum

df1 = df.groupby(level='dex1').sum()
print (df1)
      one  two
dex1          
H      12   15
I       6    6

从pandas版本0.20.0可能是omit level参数。

df1 = df.groupby('dex1').sum()
print (df1)
      one  two
dex1          
H      12   15
I       6    6

或使用DataFrame.sum参数level

df1 = df.sum(level=0)
print (df1)
      one  two
dex1          
H      12   15
I       6    6
df1 = df.sum(level='dex1')
print (df1)
      one  two
dex1          
H      12   15
I       6    6