3

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]])
3
  • 1
    I'm confused -- What do a and b have to do with anything? Also, hy were the numbers 90,91,100,101,102,110 ... chosen? Commented Jun 4, 2013 at 13:36
  • @mgilson they correspond to c when viewed as two dimensional indices Commented Jun 4, 2013 at 13:36
  • @jamylak -- Ahh ... Alright ... Now I've got it :) Thanks. Commented Jun 4, 2013 at 13:39

1 Answer 1

8

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

The index trick c_ will do the same: np.c_[c, b[tuple(c.T)]]
Thank you! I think I would have died from inanition before finding the answer myself... :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.