Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 823
ajwood Avatar asked Jan 10 '12 18:01

ajwood


1 Answers

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]
like image 51
Fred Foo Avatar answered Sep 21 '22 09:09

Fred Foo