2

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]]
0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.