What's the best way to sum all values in a Pandas dataframe?

Bill picture Bill · Aug 3, 2016 · Viewed 33.3k times · Source

I figured out these two methods. Is there a better one?

>>> import pandas as pd
>>> df = pd.DataFrame({'A': [5, 6, 7], 'B': [7, 8, 9]})
>>> print df.sum().sum()
42
>>> print df.values.sum()
42

Just want to make sure I'm not missing something more obvious.

Answer

piRSquared picture piRSquared · Aug 3, 2016

Updated for Pandas 0.24+

df.to_numpy().sum()

Prior to Pandas 0.24+

df.values

Is the underlying numpy array

df.values.sum()

Is the numpy sum method and is faster