Sum of several columns from a pandas dataframe

后端 未结 2 683
甜味超标
甜味超标 2021-02-15 15:01

So say I have the following table:

In [2]: df = pd.DataFrame({\'a\': [1,2,3], \'b\':[2,4,6], \'c\':[1,1,1]})

In [3]: df
Out[3]: 
   a  b  c
0  1  2  1
1  2  4           


        
相关标签:
2条回答
  • 2021-02-15 15:42

    I think you can use double sum - first DataFrame.sum create Series of sums and second Series.sum get sum of Series:

    print (df[['a','b']].sum())
    a     6
    b    12
    dtype: int64
    
    print (df[['a','b']].sum().sum())
    18
    

    You can also use:

    print (df[['a','b']].sum(axis=1))
    0    3
    1    6
    2    9
    dtype: int64
    
    print (df[['a','b']].sum(axis=1).sum())
    18
    

    Thank you pirSquared for another solution - convert df to numpy array by values and then sum:

    print (df[['a','b']].values.sum())
    18
    

    print (df.sum().sum())
    21
    
    0 讨论(0)
  • 2021-02-15 15:42

    Maybe you are looking something like this:

    df["result"] = df.apply(lambda row: row['a' : 'c'].sum(),axis=1)
    
    0 讨论(0)
提交回复
热议问题