[SciPy-User] Reshaping Question
Anne Archibald
peridot.faceted at gmail.com
Wed Nov 4 21:05:54 EST 2009
2009/11/4 David Warde-Farley <dwf at cs.toronto.edu>:
> Hi Skipper,
>
> No, I don't believe so. The reason is that NumPy arrays have to obey constant stride along each dimension. Assuming
> dtype is int32, the reshaping you describe (assuming you want to reshape c into d) would require the stride along dim
> 2 to be 4 bytes to get from 0 to 1, and then 12 bytes to get to 4, and then 4 bytes again to get to 5. This isn't
> legal, you'd have to do a copy to construct this matrix.
Reshape sometimes creates copies. It tries hard not to, and if you
assign the shape attribute rather than calling reshape it won't ever
make a copy, but if necessary reshape will copy the input array:
In [42]: np.transpose(c.reshape(2,2,2,2),(0,2,1,3)).reshape(4,4)Out[42]:
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]])
The trick is to use transpose to do an arbitrary permutation of the
input axes, and also to rearrange the first axis with an additional
reshape.
Anne
> David
>
> On Wed, Nov 04, 2009 at 08:25:12PM -0500, Skipper Seabold wrote:
>> My brain is failing me. Is there a clean way to reshape an array like
>> the following?
>>
>> import numpy as np
>>
>> c = np.arange(16).reshape(4, 2, 2)
>>
>> In [209]: c
>> Out[209]:
>> array([[[ 0, 1],
>> [ 2, 3]],
>>
>> [[ 4, 5],
>> [ 6, 7]],
>>
>> [[ 8, 9],
>> [10, 11]],
>>
>> [[12, 13],
>> [14, 15]]])
>>
>> So that c == d where
>>
>> d = np.array(([0, 1, 4, 5], [2,3,6,7], [8,9,12,13], [10, 11, 14, 15]))
>>
>> In [211]: d
>> Out[211]:
>> array([[ 0, 1, 4, 5],
>> [ 2, 3, 6, 7],
>> [ 8, 9, 12, 13],
>> [10, 11, 14, 15]])
>>
>> Cheers,
>>
>> Skipper
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User at scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
More information about the SciPy-User
mailing list