Skip to main content
 首页 » 编程设计

python之np.reshape(x, (-1,1)) vs x[ :, np.newaxis]

2025年02月15日7telwanggs

我最近在阅读一个开源项目的源代码。当程序员想要将像 array([0, 1, 2]) 这样的行向量转换为像 array([[0], [1], [2]] 这样的列向量时),使用了 np.reshape(x, (-1,1))。 在评论中,它说 reshape 对于保持数据连续性是必要的,而 [:, np.newaxis] 则不需要。

这两种方式我都试过了,好像返回的结果是一样的。那么这里的数据连续性保存是什么意思呢?

请您参考如下方法:

两种方式都返回完全相同数据的 View ,因此“数据连续性”可能不是问题,因为数据没有改变,只是 View 发生了改变。参见 Numpy: use reshape or newaxis to add dimensions .

然而,使用 .reshape((-1,1)) 可能有一个实际优势,因为它会将数组 reshape 为二维数组,而不管原始形状如何。对于 [:, np.newaxis],结果将取决于数组的原始形状,考虑到这些:

In [3]: a1 = np.array([0, 1, 2]) 
 
In [4]: a2 = np.array([[0, 1, 2]]) 
 
In [5]: a1.reshape((-1, 1)) 
Out[5]:  
array([[0], 
       [1], 
       [2]]) 
 
In [6]: a2.reshape((-1, 1)) 
Out[6]:  
array([[0], 
       [1], 
       [2]]) 
 
In [7]: a1[:, np.newaxis] 
Out[7]:  
array([[0], 
       [1], 
       [2]]) 
 
In [8]: a2[:, np.newaxis] 
Out[8]: array([[[0, 1, 2]]])