Sum all columns of an array using numpy. Is there a better way to do it?

Asked

Viewed 3,590 times

1

I did so:

import numpy as np

#soma de todas as colunas de mat!

mat = np.arange(1,26).reshape(5,5)
print(mat)

lista =[]
for i in np.arange(0,len(mat)):
    lista.append(np.sum(mat[0:,i:i+1]))

print(np.array(lista))

The exit is correct:

[55 60 65 70 75]

Is there any better way to do using some numpy function?

1 answer

4


You can calculate the sum of the columns directly with the function sum, informing the parameter: axis 0 ('Axis=0'):

In [20]: mat.sum(axis=0)
Out[20]: array([55, 60, 65, 70, 75])

Documentation: sum

  • did not understand the parameter Axis. Could you please explain?

  • 1

    The parameter Axis indicates on which axis (in a matrix 2d) the operation will be done. axis=0 indicates that the sum will be done in all rows of each column ("vertical"). axis=1 indicates that the sum will be done in all columns of each row ("horizontal").

Browser other questions tagged

You are not signed in. Login or sign up in order to post.