djokovic
djokovic

Reputation: 43

Replacing a row in 2d numpy array

I am trying to replace a row in a 2d numpy array.

array2d = np.arange(20).reshape(4,5)
for i in range(0, 4, 1):
    array2d[i] = array2d[i] / np.sum(array2d[i])

but I'm getting all 0s:

 [[0 0 0 0 0]
     [0 0 0 0 0]
     [0 0 0 0 0]
     [0 0 0 0 0]]

The expected result is:

[[0 0.1 0.2 0.3 0.4]
 [0.14285714 0.17142857 0.2        0.22857143 0.25714286]
 [0.16666667 0.18333333 0.2        0.21666667 0.23333333]
 [0.17647059 0.18823529 0.2        0.21176471 0.22352941]]

Upvotes: 2

Views: 1007

Answers (1)

kuzand
kuzand

Reputation: 9806

The reason you are getting 0's is because the array's dtype is int but the division returns floats in range 0 to 1 and because you modify the rows in-place they are converted to integers (i.e. to 0 in your example). So to fix it use array2d = np.arange(20, dtype=float).reshape(4,5).

But there is no need for the for-loop:

array2d = np.arange(20).reshape(4,5)
array2d = array2d / np.sum(array2d, axis=1, keepdims=True)

Note that here I didn't specify the dtype of the array to be float, but the resulting array's dtype is float because on the second line we created a new array instead of modifying the first array in-place.

https://numpy.org/doc/stable/user/basics.indexing.html#assigning-values-to-indexed-arrays

Upvotes: 4

Related Questions