[Numpy-discussion] indexing question

Robin robince at gmail.com
Thu Mar 5 16:34:36 EST 2009


On Thu, Mar 5, 2009 at 9:15 PM, Stéfan van der Walt <stefan at sun.ac.za> wrote:
> Hi Robin
>
> 2009/3/5 Robin <robince at gmail.com>:
>> On Thu, Mar 5, 2009 at 10:57 AM, Robin <robince at gmail.com> wrote:
>>> On Thu, Mar 5, 2009 at 10:40 AM, Robin <robince at gmail.com> wrote:
>>>> Hi,
>>>>
>>>> I have an indexing problem, and I know it's a bit lazy to ask the
>>>> list, sometime when people do interesting tricks come up so I hope no
>>>> one minds!
>>>>
>>>> I have a 2D array X.shape = (a,b)
>>>>
>>>> and I want to change it into new array which is shape (2,(a*b)) which
>>>> has the following form:
>>>> [  X[0,0], X[0,1]
>>>>   X[1,0], X[1,1]
>>>>   X[2,0], X[2,1]
>>>>   ....
>>>>   X[a,0], X[a,1]
>>>>   X[0,1], X[0,2]
>>>>   X[1,1], X[1,2]
>>>> ...
>>>> ]
>>>>
>
> >From the array you wrote down above, I assume you meant ((a*b-1), 2):
>
> In [23]: x = np.arange(16).reshape((4,4))
>
> In [24]: x
> Out[24]:
> array([[ 0,  1,  2,  3],
>       [ 4,  5,  6,  7],
>       [ 8,  9, 10, 11],
>       [12, 13, 14, 15]])
>
> In [25]: x.strides
> Out[25]: (16, 4)
>
> In [26]: np.lib.stride_tricks.as_strided(x, shape=(3, 4, 2), strides=(4, 16, 4))
> Out[26]:
> array([[[ 0,  1],
>        [ 4,  5],
>        [ 8,  9],
>        [12, 13]],
>
>       [[ 1,  2],
>        [ 5,  6],
>        [ 9, 10],
>        [13, 14]],
>
>       [[ 2,  3],
>        [ 6,  7],
>        [10, 11],
>        [14, 15]]])
>
> In [27]: np.lib.stride_tricks.as_strided(x, shape=(3, 4, 2),
> strides=(4, 16, 4)).reshape((12, 2))
> Out[27]:
> array([[ 0,  1],
>       [ 4,  5],
>       [ 8,  9],
>       [12, 13],
>       [ 1,  2],
>       [ 5,  6],
>       [ 9, 10],
>       [13, 14],
>       [ 2,  3],
>       [ 6,  7],
>       [10, 11],
>       [14, 15]])
>
> Does that help?

Ah thats great thanks... I had realised it could be done with
as_strided and a reshape from your excellent slides - but I had
trouble figure out the new strides so I settled on making a list with
_ix and the hstack'ing the list.

This is much neater though.

Thanks,

Robin



More information about the NumPy-Discussion mailing list