Phước Hữu Lưu Phước Hữu Lưu - 3 years ago 260
Python Question

Cant get Element of List in Numpy

I am trying to calculate the sum of all

1d matrices
in a list (as the code below), but I can't get the element of the output array.
I cant explain the reason why?

Here is my Code:

import numpy as np
from functools import reduce
matrix = np.matrix([[1,2,3],[2,3,4],[1,1,1]])
my_sum_matrix = reduce(lambda x,y : x + y, matrix)
print (my_sum_matrix)
print (my_sum_matrix[0])

And this is output :

[[4 6 8]]
[[4 6 8]]

Answer Source

The Numpy matrix type should only be used when you really need it. For more general work, you should use the array type. And you don't need reduce for this task.

import numpy as np

matrix = np.array([[1,2,3], [2,3,4], [1,1,1]])
my_sum_matrix = np.sum(matrix, axis=0)


[4 6 8]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download