为什么在 numpy 的 expand_dims 中使用 -2 索引
Why use a -2 index in numpy's expand_dims
我正在审查别人的代码(使用 numpy 1.16.3),发现了一条令人费解的线,在 expand_dims
中以 -2
作为扩展轴:
result = [np.expand_dims(v != 0, -2) for v in vecs]
查看文档,我发现了这条注释:
Note
Previous to NumPy 1.13.0, neither axis < -a.ndim - 1 nor axis > a.ndim raised errors or put the new axis where documented. Those axis values are now deprecated and will raise an AxisError in the future.
这让我觉得 -2
只会让 expand_dims
什么都不做。
是这样吗?如果是这样,为什么还要在代码中使用它?它只是一种包装逻辑评估的方法吗v != 0
?
如果将负 axis
值传递给 numpy.expand_dims
,新轴将放置在新数组形状中的那个位置。例如,
In [1]: import numpy
In [2]: x = numpy.zeros((3, 4, 5))
In [3]: numpy.expand_dims(x, -2).shape
Out[3]: (3, 4, 1, 5)
此处,新轴位于新形状的索引 -2 处。这遵循负索引的标准 Python 规则:-1 是最后一个元素,-2 是倒数第二个元素,等等。请注意,这是相对于 new形状,而不是旧形状;新形状的索引 -2 是旧形状的索引 -1。
我正在审查别人的代码(使用 numpy 1.16.3),发现了一条令人费解的线,在 expand_dims
中以 -2
作为扩展轴:
result = [np.expand_dims(v != 0, -2) for v in vecs]
查看文档,我发现了这条注释:
Note
Previous to NumPy 1.13.0, neither axis < -a.ndim - 1 nor axis > a.ndim raised errors or put the new axis where documented. Those axis values are now deprecated and will raise an AxisError in the future.
这让我觉得 -2
只会让 expand_dims
什么都不做。
是这样吗?如果是这样,为什么还要在代码中使用它?它只是一种包装逻辑评估的方法吗v != 0
?
如果将负 axis
值传递给 numpy.expand_dims
,新轴将放置在新数组形状中的那个位置。例如,
In [1]: import numpy
In [2]: x = numpy.zeros((3, 4, 5))
In [3]: numpy.expand_dims(x, -2).shape
Out[3]: (3, 4, 1, 5)
此处,新轴位于新形状的索引 -2 处。这遵循负索引的标准 Python 规则:-1 是最后一个元素,-2 是倒数第二个元素,等等。请注意,这是相对于 new形状,而不是旧形状;新形状的索引 -2 是旧形状的索引 -1。