Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Tags:

python

numpy

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?

like image 720
Puggie Avatar asked Nov 26 '12 14:11

Puggie


People also ask

How do I sum all columns in an array Numpy?

sum() in Python. The numpy. sum() function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array.

How do you sum a 2D numpy array?

To get the sum of each column in a 2D numpy array, pass axis=0 to the sum() function. This argument tells the function of the axis along which the elements are to be summed.

How do I sum a 2D array column in Python?

Python3. Method 2: Using the sum() function in NumPy, numpy. sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.


1 Answers

Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:

>>> import numpy as np >>> a = np.arange(12).reshape(4,3) >>> a.sum(axis=0) array([18, 22, 26]) 

Or, to sum over rows:

>>> a.sum(axis=1) array([ 3, 12, 21, 30]) 

Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.

From the Tentative Numpy Tutorial:

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

like image 143
John Vinyard Avatar answered Oct 06 '22 10:10

John Vinyard