array indexing question

10 views
Skip to first unread message

Nick C

unread,
Jan 24, 2013, 8:59:08 PM1/24/13
to scipy...@googlegroups.com
I'm fairly new to this, so apologies in advance.  
Let's say I have a 3-d array A[i,j,k] of shape (Ni,Nj,Nk), and a list of labels I[k], where I[k] belongs to 0...Ni-1.
I want to create a new, 2-d array B[j,k] = A[I[k], j, k].
I've found one solution to this, which is:
ind_i = np.tile(I, (1,Nj)).T
ind_j = np.tile(np.arange(Nj), (1,Nk))
ind_k = np.tile(np.arange(Nk), (1, Nj)).T
B = A[ind_i, ind_j, ind_k]

but something seems...not ideal about this.  Can someone tell me if there's a simpler, better way?
Thanks,
Nick

Nick C

unread,
Jan 24, 2013, 9:13:15 PM1/24/13
to scipy...@googlegroups.com
Ok, I think I found an improvement, myself; actually, it is a big improvement syntactically, and is perhaps more efficient:
B = A[I[np.newaxis, :], np.arange(Nj)[:, np.newaxis], np.arange(Nk)[np.newaxis, :]]

but is this the "right" way to do things?
-Nick
Reply all
Reply to author
Forward
0 new messages