How do you reduce the dimension of a numpy array?

前端 未结 2 1105
甜味超标
甜味超标 2021-01-13 02:38

I started with an mxnxp array, A,

In [16]: A
Out[16]: 
array([[[  2.10000000e+01,   3.70060693e-01],
        [  2.00000000e+01,   2         


        
相关标签:
2条回答
  • 2021-01-13 02:53

    You could use numpy.squeeze()

    x = np.array([[[0], [1], [2]]])
    x.shape
    (1, 3, 1)
    np.squeeze(x).shape
    (3,)
    np.squeeze(x, axis=(2,)).shape
    (1, 3)
    
    0 讨论(0)
  • 2021-01-13 02:57

    I stumbled upon A.reshape(1,27,1) and first without conserving the size and I got a

    ValueError: total size of new array must be unchanged
    

    error, but then accidentally, I ended up trying omitting the third dimension in the reshape,

    In [21]: A[:,:,:1].reshape(2,27)
    Out[21]: 
    array([[ 21.,  20.,  15.,  23.,  22.,  16.,  25.,  24.,  12.,   4.,   7.,
              1.,   6.,   3.,  19.,  13.,  11.,   9.,   8.,  27.,  14.,  18.,
             10.,  17.,  26.,   2.,   5.],
           [ 20.,  21.,  12.,   1.,  17.,   4.,  22.,  23.,  16.,   6.,  15.,
             26.,  13.,  19.,  24.,   2.,  10.,  25.,   3.,   7.,   8.,  11.,
             27.,  14.,   9.,  18.,   5.]])
    

    and magically the third dimension disappeared.

    And this is exactly what I wanted.

    0 讨论(0)
提交回复
热议问题