[Numpy-discussion] indexing question

Stéfan van der Walt stefan@sun.ac...
Thu Mar 5 15:15:40 CST 2009


Hi Robin

2009/3/5 Robin <robince@gmail.com>:
> On Thu, Mar 5, 2009 at 10:57 AM, Robin <robince@gmail.com> wrote:
>> On Thu, Mar 5, 2009 at 10:40 AM, Robin <robince@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?

Regards
Stéfan


More information about the Numpy-discussion mailing list