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

标签 python numpy

我最近在阅读一个开源项目的源代码。当程序员想要将像 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]]])

关于python - np.reshape(x, (-1,1)) vs x[ :, np.newaxis],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334014/

相关文章:

python - 根据 Numpy 中的动态条件替换子数组中的值

python - Python 中存在 MemoryError,但 IPython 中没有

python - 映射 pandas DataFrame 索引

python - 子类化 logging.Formatter 更改 logging.Formatter 的默认行为

python - 如何在 Python 中使用 numpy 将 3D 矩阵和 2D 矩阵相乘?

python - 如何使用 nans 对 pandas 列进行 zscore 标准化?

python - 继续运行到 "TypeError: ' numpy.float6 4' object is not callable"

python - 使用numpy和scipy将wrf数据的网格点插值到python中的lat lon

python - 我应该在 UiPath 中使用 Python 的示例案例有哪些?

python - 查找对 numpy 列进行排序的索引返回零