简体   繁体   中英

python - Replacing value in a numpy array's column given index from a vector with the same rows

A = np.zeros(shape = (3,4))
A = [[0 0 0 0]
     [0 0 0 0]
     [0 0 0 0]]

B = np.asarray[[2],[0],[3]]

Without a for loop, is there a simple way to change the value of the a components in A (to 1 for example), given the index in B

Such that:

A = [[0 0 1 0]
     [1 0 0 0]
     [0 0 0 1]]

I have been able to get this output with a for loop but would prefer it if it didn't for scalability in higher dimensional arrays.

Take a look at numpy's advanced indexing .

You can do

A[[0, 1, 2], [2, 0, 3]] = 1

We are indexing to fetch 3 locations and set a value, thus the lists used to index are each len 3. And A has 2 dims, so we use two lists (you can also use only one list if you want to fetch full rows).

It also works with arrays

A[np.arange(A.shape[0]), [2, 0, 3]] = 1

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