1

Say I have an array

a = np.zeros((3, 3, 3))

and a z-index array

z = np.random.randint(0, 3, (3, 3))

say z is

array([[1, 0, 2],
       [2, 2, 1],
       [1, 1, 0]])

Now I want to select the values of a with coordinates (starting at top left of z and traversing the array row-wise. Column-wise would be fine too.) (0, 0, 1), (0, 1, 0), (0, 2, 2), ... . The bold values are from the z array.

2
  • is a supposed to be a 3d array? Commented Apr 4, 2014 at 10:06
  • Yes, sorry. Fixed it. Commented Apr 4, 2014 at 10:08

1 Answer 1

1

I think this does what you want.

import numpy as np 

a = np.arange(3*3*3).reshape(3,3,3)
z = np.array([[1, 0, 2],
       [2, 2, 1],
       [1, 1, 0]])
i = np.arange(a.shape[0]).repeat(a.shape[0]).reshape(a.shape[0], a.shape[1])
j = i.T
#Should do the same as this. possible more efficient, did not test.
#i, j = np.indices(a[...,0].shape)
print a[i,j,z]
Sign up to request clarification or add additional context in comments.

2 Comments

Nope. If I use zeros and then a[i,j,z] = 1, a[0, 0 ,0] is 1 but should be 0.
It works if i is array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) and j is i.T.

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.