close

How do you reduce the dimension of a numpy array?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do you reduce the dimension of a numpy array in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do you reduce the dimension of a numpy array?

  1. How do you reduce the dimension of a numpy array?

    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

  2. you reduce the dimension of a numpy array

    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

Method 1

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)

Method 2

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.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read