Python Numpy Vector (N,1) 维 -> (N,) 维转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17869840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:21:30  来源:igfitidea点击:

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

pythonarraysnumpy

提问by Tom Bennett

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

我有一个关于 (N,) 维数组和 (N,1) 维数组之间转换的问题。例如,y 是 (2,) 维。

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.

但以下将显示 y2 为 (2,1) 维。

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?

在不复制的情况下将 y2 转换回 y 的最有效方法是什么?

Thanks, Tom

谢谢,汤姆

采纳答案by tom10

reshapeworks for this

reshape为此工作

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 reshapedoesn't copy the data unless it needs to for the new shape (which it doesn't need to do here):

另请注意,reshape除非需要为新形状复制数据(此处不需要这样做),否则不会复制数据:

a.__array_interface__['data']   # (22356720, False)
b.__array_interface__['data']   # (22356720, False)
c.__array_interface__['data']   # (22356720, False)

回答by ely

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

沿着您想要的尺寸切片,如下例所示。反过来,您可以将None任何维度用作切片,这些维度应该被视为单一维度,但它是使形状工作所必需的。

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:

或者,您可以使用reshape

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

回答by Hanan Shteingart

the opposite translation can be made by:

可以通过以下方式进行相反的翻译:

np.atleast_2d(y).T

回答by dbliss

Use numpy.squeeze:

使用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)

回答by user10296606

What about vice versa? Numpy Numpy Vector (N,) dimension conversion ->Vector (N,1) dimension dimension conversion

反过来呢?Numpy Numpy Vector(N,)维度转换->Vector(N,1)维度维度转换