0

While executing the below code I'm simply getting the first row(split) of the matrix back not the sum of the elements as what I'm expecting. Is my understanding incorrect or did I do something stupid?

My objective is to get the sum of all elements in each row.

import numpy as np
from functools import reduce

matrix = 100*np.random.rand(4,4)
matrix=matrix.astype(int)
print(matrix)
s_matrix = np.vsplit(matrix, 4)
sum_test = reduce((lambda a,b : a+b), list(s_matrix[0]))
print(sum_test)

Output:

[[79 75 33 26]
[49 45 16 19]
[58 33 83 55]
[40 14  2 93]]

[79 75 33 26]

Expected:

[213, 129, 229, 149]
Codistan
  • 1,469
  • 1
  • 13
  • 17

3 Answers3

2

Check the expression you're using: print(list(s_matrix[0])). I think you'll find that it's a double-nested list

[[79 75 33 26]]

Thus, the "sum" is merely concatenation of a single list element.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Thanks for the clarification. I got the hang of it now but my objective is to get the sum of all elements in each row. I fixed the code by passing the whole matrix but now I think its adding elements column wise. Passing s_matrix[0] did not work. – Codistan Jul 24 '19 at 17:18
  • Ok I understand that its concatenation. Any suggestions on how I can get the sum of each row? – Codistan Jul 24 '19 at 17:25
  • 1
    Why are you writing your own function instead of applying the `sum` method, row-wise? – Prune Jul 24 '19 at 17:27
1

You can use reduce() for this by continually adding the results to a list in the accumulator:

import numpy as np
from functools import reduce

matrix = 100*np.random.rand(4,4)
matrix=matrix.astype(int)
sum_test = reduce(lambda a,b : a+[sum(b)], list(matrix), [])
print(sum_test)

...but you really shouldn't. One of the major points of Numpy is that you can avoid explicit python loops. Instead you should just use the array's sum function. You can pass it an axis to tell it to sum rows instead of the whole thing:

import numpy as np

matrix = np.random.randint(0, 100, [4,4])
print(matrix)
print(matrix.sum(axis = 1))

Result

[[64 89 97 15]
 [12 47 81 31]
 [52 81 37 78]
 [27 64 79 50]]

[265 171 248 220]
Mark
  • 90,562
  • 7
  • 108
  • 148
-1

sum_test = reduce((lambda a,b : a+b), list(s_matrix[0]))

above line is your problem,

you are only giving the first row of your matrix instead of giving the whole matrix

Aly Zayn
  • 61
  • 1
  • 4
  • This doesn't address the question, to wit, why didn't the code produce the *sum* of that one row? – Prune Jul 24 '19 at 17:21
  • He needs to convert this into a single list array([[92, 98, 34, 24]]), that's why it does not sum the first row – Aly Zayn Jul 24 '19 at 20:40