Sum of several columns from a pandas dataframe
<p>So say I have the following table:</p>

<pre><code>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  1
2  3  6  1
</code></pre>

<p>I can sum a and b that way:</p>

<pre><code>In [4]: sum(df['a']) + sum(df['b'])
Out[4]: 18
</code></pre>

<p>However this is not very convenient for larger dataframe, where you have to sum multiple columns together.</p>

<p>Is there a neater way to sum columns (similar to the below)? What if I want to sum the entire DataFrame without specifying the columns?</p>

<pre><code>In [4]: sum(df[['a', 'b']]) #that will not work!
Out[4]: 18
In [4]: sum(df) #that will not work!
Out[4]: 21
</code></pre>

<p>I think you can use double <code>sum</code> - first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>DataFrame.sum</code></a> create <code>Series</code> of sums and second <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>Series.sum</code></a> get sum of <code>Series</code>:</p>

<pre><code>print (df[['a','b']].sum())
a     6
b    12
dtype: int64

print (df[['a','b']].sum().sum())
18
</code></pre>

<p>You can also use:</p>

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

print (df[['a','b']].sum(axis=1).sum())
18
</code></pre>

<p>Thank you <a href="http://stackoverflow.com/questions/40116219/sum-of-several-columns-from-a-pandas-dataframe/40116249?noredirect=1#comment67506082_40116249">pirSquared</a> for another solution - convert <code>df</code> to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a> and then <code>sum</code>:</p>

<pre><code>print (df[['a','b']].values.sum())
18
</code></pre>

<hr>

<pre><code>print (df.sum().sum())
21
</code></pre>

python pandas dataframe