Reshaping a numpy array in python

前端 未结 1 478
春和景丽
春和景丽 2020-12-10 21:41

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 elemen

相关标签:
1条回答
  • 2020-12-10 22:40

    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 讨论(0)
提交回复
热议问题