Let’s say I have the following 2D numpy array consisting of four rows and three columns:
>>> a = numpy.arange(12).reshape(4,3)
>>> print(a)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
What would be an efficient way to generate a 1D array that contains the sum of all columns (like [18, 22, 26])? Can this be done without having the need to loop through all columns?
Check out the documentation for
numpy.sum, paying particular attention to theaxisparameter. To sum over columns:Or, to sum over rows:
Other aggregate functions, like
numpy.mean,numpy.cumsumandnumpy.std, e.g., also take theaxisparameter.From the Tentative Numpy Tutorial: