this is my current code:
M = np.array([[1, 2, 3],
[4, 5, 6]])
def np_sum_rows(M):
rows = []
for i in range(len(M)):
rows = M[i, 0:len(M[0])
return rows.sum()
I want the function to return a vector [6 15]. However, the for loop can only store and return 15. I am positively stumped by this problem and cannot think of any way else but using the for loop.
CodePudding user response:
You can use a list comprehension to sum up the rows in the 2D array and return a list of the sums. Here is one way to do it:
def sum_rows(M):
return [sum(row) for row in M]
This function takes in a 2D array M and returns a list of the sums of each row in M.
Here is an example of how you can use this function:
M = np.array([[1, 2, 3], [4, 5, 6]])
print(sum_rows(M)) # [6, 15]
CodePudding user response:
You could apply reduce
method that comes from functional programming background. It's possible in both Python and numpy
-based ways.
In Python you need to apply function of two arguments cumulatively to the items of sequence.
import functools
M = M.tolist() #convert array to list in order to make iteration faster
[reduce(lambda x, y: x y, m) for m in M]
>>> [6, 15]
In numpy
you don't need to define a function usually. Universal functions (or ufunc
for short) such as add
, multiply
etc. are used instead.
np.add.reduce(M, axis=1)
>>> array([ 6, 15])
Note that more common way is to apply np.sum
on axis 1. So it's strongly adviced to get used to a concept of numpy
axes.