roudan
roudan

Reputation: 4200

convert 2D array into 1D array using np.newaxis

I am trying to convert 2D array with one column into 1D vector using np.newaxis. The result I got so far is 3D array instead of 1D vector or 1D array.

The 2D array y1 is:

y1.shape
(506, 1)

y1
array([[0.42      ],
       [0.36666667],
       [0.66      ],
       [0.63333333],
       [0.69333333],
       ... ])

Now I'd like to convert it into 1D array

import numpy as np
y2=y1[np.newaxis,:]
y2.shape
(1, 506, 1)

You can see after using np.newaxis, the shape of y2 become a 3D array, I am expecting the shape of (506,) 1D array.

what is the problem of my above code? Thanks

Upvotes: 0

Views: 161

Answers (2)

Corralien
Corralien

Reputation: 120399

np.newaxis expand dimension so 2D -> 3D. If you want to reduce your dimension 2D -> 1D, use squeeze:

>>> a
array([[0.42      ],
       [0.36666667],
       [0.66      ],
       [0.63333333],
       [0.69333333]])

>>> a.shape()
(5, 1)

>>> a.squeeze()
array([0.42      , 0.36666667, 0.66      , 0.63333333, 0.69333333])

>>> a.squeeze().shape
(5,)

From the documentation:

Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.

Upvotes: 2

Prakash Dahal
Prakash Dahal

Reputation: 4875

np.newaxis() is used to increase the dimension of the array. It will not decrease the dimension. In order to decrease the dimension, you can use: reshape()

y1 = np.array(y1).reshape(-1,)

print(y1.shape)
>>> (506,)

Upvotes: 2

Related Questions