Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Vector (N,1) dimension -> (N,) dimension conversion

I have a question regarding the conversion between (N,) dimension arrays and (N,1) dimension arrays. For example, y is (2,) dimension.

A=np.array([[1,2],[3,4]])  x=np.array([1,2])  y=np.dot(A,x)  y.shape Out[6]: (2,) 

But the following will show y2 to be (2,1) dimension.

x2=x[:,np.newaxis]  y2=np.dot(A,x2)  y2.shape Out[14]: (2, 1) 

What would be the most efficient way of converting y2 back to y without copying?

Thanks, Tom

like image 228
Tom Bennett Avatar asked Jul 25 '13 22:07

Tom Bennett


People also ask

How do you make a numpy array 1-dimensional to 2-dimensional?

convert a 1-dimensional array into a 2-dimensional array by adding new axis. a=np. array([10,20,30,40,50,60]) b=a[:,np. newaxis]--it will convert it to two dimension.

How do you change the dimension of a numpy array?

The shape of the array can also be changed using the resize() method. If the specified dimension is larger than the actual array, The extra spaces in the new array will be filled with repeated copies of the original array.

How do you reshape a numpy array in one direction?

Flattening array means converting a multidimensional array into a 1D array. We can use reshape(-1) to do this.

How do you transpose a one direction vector numpy?

If you want to convert your 1D vector into the 2D array and then transpose it, slice it with numpy np. newaxis (or None, they are the same; the new axis is only more readable).


2 Answers

reshape works for this

a  = np.arange(3)        # a.shape  = (3,) b  = a.reshape((3,1))    # b.shape  = (3,1) b2 = a.reshape((-1,1))   # b2.shape = (3,1) c  = b.reshape((3,))     # c.shape  = (3,) c2 = b.reshape((-1,))    # c2.shape = (3,) 

note also that reshape doesn't copy the data unless it needs to for the new shape (which it doesn't need to do here):

a.__array_interface__['data']   # (22356720, False) b.__array_interface__['data']   # (22356720, False) c.__array_interface__['data']   # (22356720, False) 
like image 173
tom10 Avatar answered Sep 23 '22 08:09

tom10


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) 
like image 41
dbliss Avatar answered Sep 23 '22 08:09

dbliss