Raoul
Raoul

Reputation: 1902

Merging two arrays under numpy

Using Numpy, I would like to achieve the result below, given b and c. I have looked into stacking functions, but I cannot get it to work. Could someone please help?

import numpy as np

a=range(35,135)

b=np.reshape(a,(10,10))
c=np.array([[5,5],[5,6],[5,7],[6,5],[6,6],[6,7],[7,5],[7,6],[7,7]])

The result should look like this:

np.array([[5,5,90],[5,6,91],[5,7,92],[6,5,100],[6,6,101],[6,7,102],
          [7,5,110],[7,6,111],[7,7,112]])

Upvotes: 3

Views: 1580

Answers (1)

mgilson
mgilson

Reputation: 310287

Phew! This was a doosie. First, we use numpy's fancy indexing to pull out the items that you want.:

>>> b[tuple(c.T)]
array([ 90,  91,  92, 100, 101, 102, 110, 111, 112])

Then, the only thing that remains is to stack that array back against c using column_stack:

>>> np.column_stack((c,b[tuple(c.T)]))
array([[  5,   5,  90],
       [  5,   6,  91],
       [  5,   7,  92],
       [  6,   5, 100],
       [  6,   6, 101],
       [  6,   7, 102],
       [  7,   5, 110],
       [  7,   6, 111],
       [  7,   7, 112]])

Upvotes: 8

Related Questions