简体   繁体   中英

How do I do this array indexing in numpy

Given an index array I , how to I set the values of a data array D whose indices don't exist in I ?

Example: How to I get A from I and D ?

I = array( [[1,1], [2,2], [3,3]] )

D = array( [[ 1, 2, 3, 4, 5, 6],
            [ 7, 8, 9, 1, 2, 3],
            [ 4, 5, 6, 7, 8, 9],
            [ 1, 2, 3, 4, 5, 6],
            [ 7, 8, 9, 1, 2, 3]] )

A = array( [[ 0, 0, 0, 0, 0, 0],
            [ 0, 8, 0, 0, 0, 0],
            [ 0, 0, 6, 0, 0, 0],
            [ 0, 0, 0, 4, 0, 0],
            [ 0, 0, 0, 0, 0, 0]] )

Edit: I'm looking for how to do this in one shot for cases where I and d are big.

Simple solution:

A = zeros(D.shape)
for i, j in I:
    A[i, j] = D[i, j]

Vectorized:

A = zeros(D.shape)
i, j = I.T
A[i, j] = D[i, j]

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