Numpy: Create a 1D array of numpy arrays when all arrays have the same length

前端 未结 4 735
有刺的猬
有刺的猬 2021-01-14 05:48

I want to be able to convert an existing 2D array to a 1D array of arrays. The only way I can find is to use something like:

my_2d_array = np.random.random((         


        
4条回答
  •  北海茫月
    2021-01-14 05:56

    There are methods like ravel, flatten and reshape to do the job. Learn the difference between them here in this link.

    Using ravel or flatten as

    my_1d_array = my_2d_array.flatten() # Return (15,) dimension 
    my_1d_array = my_2d_array.ravel() # Return (15,) dimension
    

    Such (15,) type may inflict some inconsistency when performing some matrix operation and result inconsistent data result or program error.

    So I prefer you to use reshape as follows:

    my_1d_array = my_2d_array.reshape((-1,1)) # Returns (15,1) dimension
    or,
    my_1d_array = my_2d_array.reshape((1,-1)) # Returns (1,15) dimension
    

    This way of reshaping into (x, y) ensures matrix operation will always result consistent data without any bugs.

提交回复
热议问题