45

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

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Tom Bennett
  • 2,305
  • 5
  • 24
  • 32

5 Answers5

57

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)
tom10
  • 67,082
  • 10
  • 127
  • 137
24

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)
abcd
  • 10,215
  • 15
  • 51
  • 85
5

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])
ely
  • 74,674
  • 34
  • 147
  • 228
0

the opposite translation can be made by:

np.atleast_2d(y).T
Hanan Shteingart
  • 8,480
  • 10
  • 53
  • 66
0

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.

blunova
  • 2,122
  • 3
  • 9
  • 21