3

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 either 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.

Double AA
  • 5,759
  • 16
  • 44
  • 56

1 Answers1

6

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.

senderle
  • 145,869
  • 36
  • 209
  • 233
  • 1
    +1. This is much easier than keeping lists inside of Numpy arrays. – Fred Foo Jul 08 '11 at 17:14
  • Yes. I think what I was missing is that I really have a 3 dimensional array, 48x365x3 . I had been assuming the threes were unaffected but np treated them (correctly) as a third dimension. Keeping the extra dimension in the np.reshape(-1,3) solves the issue. Thanks – Double AA Jul 08 '11 at 17:15