简体   繁体   中英

Replacing elements in numpy array

import numpy as np

a = np.array([0.75, 0.5, 0.21])
one_list = [1] * 3
L_vec = np.diag(one_list)
L_vec[1,0] = a[0]
print(L_vec)

Expected Result:

[[1,0,0],[0.75,1,0],[0,0,1]]

Actual Result:

[[1 0 0]
 [0 1 0]
 [0 0 1]]

this is the result I got. I have no idea why.

By default dtype for np.diag is int

convert it into float so your float values from array a can replace older value

L_vec = L_vec.astype(float)

Use below code

a = np.array([0.75, 0.5, 0.21])
one_list = [1]*3
L_vec = np.diag(one_list)
L_vec = L_vec.astype(float)

L_vec[1,0] = a[0]
print(L_vec)

Output:

[[1.   0.   0.  ]
 [0.75 1.   0.  ]
 [0.   0.   1.  ]]

You can check datatype using print(L_vec.dtype)

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