Numpy 向量 (N,1) 维 ->(N,)维转换 [英] Numpy Vector (N,1) dimension -> (N,) dimension conversion

查看:39
本文介绍了Numpy 向量 (N,1) 维 ->(N,)维转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,)

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

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)

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

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

谢谢,汤姆

推荐答案

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,)

还要注意,reshape 不会复制数据,除非它需要为新形状复制数据(这里不需要这样做):

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)

这篇关于Numpy 向量 (N,1) 维 ->(N,)维转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆