Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
    
is a supposed to be a 3d array? – M4rtini Apr 4 '14 at 10:06
    
Yes, sorry. Fixed it. – tauran Apr 4 '14 at 10:08
up vote 1 down vote accepted

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]
share|improve this answer
    
Nope. If I use zeros and then a[i,j,z] = 1, a[0, 0 ,0] is 1 but should be 0. – tauran Apr 4 '14 at 10:21
    
It works if i is array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) and j is i.T. – tauran Apr 4 '14 at 10:24
    
Ok, a small edit should make it so. – M4rtini Apr 4 '14 at 10:35
1  
i,j = np.ogrid[:3,:3] would work too. – unutbu Apr 4 '14 at 11:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.