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
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.
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.
Flattening array means converting a multidimensional array into a 1D array. We can use reshape(-1) to do this.
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).
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With