开发者

Reshaping a numpy array in python

开发者 https://www.devze.com 2023-03-18 19:44 出处:网络
I have a 48x365 element numpy array where each element is a list containing 3 integers. I want to be able to turn it into a 1x17520 array with all the lists intact as elements. Using

I have a 48x365 element numpy array where each element is a list containing 3 integers. I want to be able to turn it into a 1x17520 array with all the lists intact as elements. Using

np.reshape(-1)

seems to break the elements into three separate integers and makes a 1x52560 array. So I ei开发者_如何学Gother need a new way of rearranging the original array or a way of grouping the elements in the new np.reshape array (which are still in order) back into lists of 3.

Thanks for your help.


Is there a reason you can't do it explicitly? As in:

>>> a = numpy.arange(17520 * 3).reshape(48, 365, 3)
>>> a.reshape((17520,3))
array([[    0,     1,     2],
       [    3,     4,     5],
       [    6,     7,     8],
       ..., 
       [52551, 52552, 52553],
       [52554, 52555, 52556],
       [52557, 52558, 52559]])

You could also do it with -1, it just has to be paired with another arg of the appropriate size.

>>> a.reshape((17520,-1))
array([[    0,     1,     2],
       [    3,     4,     5],
       [    6,     7,     8],
       ..., 
       [52551, 52552, 52553],
       [52554, 52555, 52556],
       [52557, 52558, 52559]])

or

>>> a.reshape((-1,3))
array([[    0,     1,     2],
       [    3,     4,     5],
       [    6,     7,     8],
       ..., 
       [52551, 52552, 52553],
       [52554, 52555, 52556],
       [52557, 52558, 52559]])

It occurred to me a bit later that you could also create a record array -- this might be appropriate in some situations:

a = numpy.recarray((17520,), dtype=[('x', int), ('y', int), ('z', int)])

This can be reshaped in the original way you tried, i.e. reshape(-1). Still, as larsmans' comment says, just treating your data as a 3d array is easiest.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号