简体   繁体   中英

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

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 (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM