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

Question:

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

Asked By: Tom Bennett

||

Answers:

Slice along the dimension you want, as in the example below. To go in the reverse direction, you can use None as the slice for any dimension that should be treated as a singleton dimension, but which is needed to make shapes work.

In [786]: yy = np.asarray([[11],[7]])

In [787]: yy
Out[787]:
array([[11],
       [7]])

In [788]: yy.shape
Out[788]: (2, 1)

In [789]: yy[:,0]
Out[789]: array([11, 7])

In [790]: yy[:,0].shape
Out[790]: (2,)

In [791]: y1 = yy[:,0]

In [792]: y1.shape
Out[792]: (2,)

In [793]: y1[:,None]
Out[793]:
array([[11],
       [7]])

In [794]: y1[:,None].shape
Out[794]: (2, 1)

Alternatively, you can use reshape:

In [795]: yy.reshape((2,))
Out[795]: array([11,  7])
Answered By: ely

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)
Answered By: tom10

the opposite translation can be made by:

np.atleast_2d(y).T
Answered By: Hanan Shteingart

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)
Answered By: abcd

Another option in your toolbox could be ravel:

>>> y2.shape
(2, 1)
>>> y_ = y2.ravel()
>>> y_.shape
(2,)

Again, a copy is made only if needed, but this is not the case:

>>> y2.__array_interface__["data"]
(2700295136768, False)
>>> y_.__array_interface__["data"]
(2700295136768, False)

For further details, you can take a look at this answer.

Answered By: blunova
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.