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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. This is much easier than keeping lists inside of Numpy arrays.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.