[SciPy-User] indexing question
Paul Hobson
pmhobson@gmail....
Fri Jan 25 13:55:35 CST 2013
On Thu, Jan 24, 2013 at 2:14 PM, Nick Choly <ncholy@gmail.com> wrote:
> 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
>
You can use a colon to grab all the elements along a dimension, e.g.,
In [48]: A = np.random.random_integers(0, 5, size=(3,4,4))
In [49]: A
Out[49]:
array([[[5, 3, 5, 5],
[2, 4, 0, 5],
[4, 3, 4, 5],
[1, 4, 0, 1]],
[[1, 1, 5, 1],
[5, 5, 4, 2],
[1, 2, 0, 2],
[1, 0, 3, 5]],
[[1, 4, 4, 4],
[0, 4, 3, 4],
[2, 2, 3, 1],
[0, 1, 0, 0]]])
In [51]: A[1, :, :]
Out[51]:
array([[1, 1, 5, 1],
[5, 5, 4, 2],
[1, 2, 0, 2],
[1, 0, 3, 5]])
In [52]: A[1, 0:2, 1:]
Out[52]:
array([[1, 5, 1],
[5, 4, 2]])
Does that help?
-paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20130125/1ec06f4d/attachment.html
More information about the SciPy-User
mailing list