2015-08-27 16 views
2

,我有以下的數據幀:如何總結所有的數值在熊貓數據幀,以產生一個價值

import pandas as pd 
source_df = pd.DataFrame({ 'gene':["foo","bar","qux","woz"], 'cell1':[5,9,1,7], 'cell2':[12,90,13,87]}) 
source_df = source_df[["gene","cell1","cell2"]] 

它看起來像這樣:

In [132]: source_df 
Out[132]: 
    gene cell1 cell2 
0 foo  5  12 
1 bar  9  90 
2 qux  1  13 
3 woz  7  87 

我想要做什麼是總和所有的數值,這應該產生一個單一的值

224 

什麼是這樣做?

我試過,但給兩個值來代替:

In [134]: source_df.sum(numeric_only=True) 
Out[134]: 
cell1  22 
cell2 202 
dtype: int64 

回答

2

你需要再次調用sum()。示例 -

In [5]: source_df.sum(numeric_only=True).sum() 
Out[5]: 224 
1

由於source_df.sum(numeric_only=True)回報和的系列,你可以簡單地總結一下在返回的系列的所有值與另一個總和():

source_df.sum(numeric_only=True).sum() 

輸出產生單個值:

224 

或者,您可以循環並統計手動總數

total = 0 
for v in source_df.sum(numeric_only=True): 
    total += v 
print(total)