2016-09-21 60 views
1

在这段代码中,我想总结每一列并将其添加为新行。 它代表sum,但它不显示新行。如何在pandas中总结列并将结果添加到新行中?

df = pd.DataFrame(g, columns=('AWA', 'REM', 'S1', 'S2')) 
df['xSujeto'] = df.sum(axis=1) 
xEstado = df.sum(axis=0) 
df.append(xEstado, ignore_index=True) 
df 

enter image description here

+3

'append'不是就地操作。您需要将其分配回原来的'DF',如'df = df.append(xEstado,ignore_index = True)'。 –

回答

4

我认为你可以使用loc

df = pd.DataFrame({'AWA':[1,2,3], 
        'REM':[4,5,6], 
        'S1':[7,8,9], 
        'S2':[1,3,5]}) 

#add 1 to last index value 
print (df.index[-1] + 1) 
3 

df.loc[df.index[-1] + 1] = df.sum() 
print (df) 
    AWA REM S1 S2 
0 1 4 7 1 
1 2 5 8 3 
2 3 6 9 5 
3 6 15 24 9 

或者append from comment of Nickil Maveli

xEstado = df.sum() 
df = df.append(xEstado, ignore_index=True) 
print (df) 
    AWA REM S1 S2 
0 1 4 7 1 
1 2 5 8 3 
2 3 6 9 5 
3 6 15 24 9