Using values in 2d matrix as lookups

Question:

I have a 2-D numpy array that I would like to use as a series of indexes. The values in the array are all integer values:

array([[3, 3, 3, 2],
       [1, 5, 2, 3],
       [4, 2, 3, 2],
       [2, 3, 1, 3]])

I also have a 1D array with 5 values

array([x,y,z,q,p])

I’d like to use the cells of the 2D array as lookup values into the 1D array. In other words, where the 2D array is equal to 1, return x. Where it’s equal to 2, return y, and so on.

This is simple enough to do in matlab, but I’d like a numpy solution that doesn’t involve looping.

Thoughts?

Asked By: Mykenk

||

Answers:

Assuming x, y, z, q, p are variables (and not characters).
If you define the first array as (say, src):

src = np.array([[3, 3, 3, 2],
            [1, 5, 2, 3],
            [4, 2, 3, 2],
            [2, 3, 1, 3]])

and the second as (say, lookup):

lookup = np.array([x,y,z,q,p])

You can get the desired output using:

lookup[src - 1]

Or if you want individual outputs:

lookup[src[i, j] - 1]

where (i, j) is the 2-D index of the value that you want to look up.
Please note that the -1 here is to account for the offset (as mentioned in the comment by slothrop)

Answered By: Dev Bhuyan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.