无的numpy索引切片
通过numpy的滑动窗口示例进行工作。试图了解,None
的start_idx =np.arange(B[0])[:,None]
foo = np.arange(10)
print foo
print foo[:]
print foo[:,]
print foo[:,None]
效果None
似乎是转置数组。
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]]
但是我不确定。我没有找到解释第二个参数(None
)的文档。对于Google来说,这也是一个艰难的片段。该numpy的阵列文档让我觉得它是与先进的索引,但我不能肯定不够。
-
foo[:, None]
将一维数组扩展foo
到第二维。实际上,numpy
使用别名np.newaxis
来做到这一点。考虑
foo
foo = np.array([1, 2]) print(foo) [1 2]
一维阵列具有局限性。例如,什么是移调?
print(foo.T) [1 2]
与数组本身相同
print(foo.T == foo) [ True True]
此限制有很多含义,
foo
在更高维度的上下文中考虑变得很有用。numpy的用途np.newaxis
print(foo[np.newaxis, :]) [[1 2]]
但这
np.newaxis
只是语法糖None
np.newaxis is None True
因此,我们通常会
None
改用它,因为它的字符更少,含义相同print(foo[None, :]) [[1 2]]
好吧,让我们看看我们还能做些什么。注意,我
None
在第一个位置使用示例,而OP在第二个位置使用示例。此位置指定要扩展的尺寸。而且我们可以采取进一步的措施。让这些例子帮助解释print(foo[None, :]) # same as foo.reshape(1, 2) [[1 2]]
print(foo[:, None]) # same as foo.reshape(2, 1) [[1] [2]]
print(foo[None, None, :]) # same as foo.reshape(1, 1, 2) [[[1 2]]]
print(foo[None, :, None]) # same as foo.reshape(1, 2, 1) [[[1] [2]]]
print(foo[:, None, None]) # same as foo.reshape(2, 1, 1) [[[1]] [[2]]]
记住numpy打印数组时哪个维度
print(np.arange(27).reshape(3, 3, 3)) dim2 ────────⇀ dim0 → [[[ 0 1 2] │ dim1 [ 3 4 5] │ [ 6 7 8]] ↓ ────────⇀ → [[ 9 10 11] │ [12 13 14] │ [15 16 17]] ↓ ────────⇀ → [[18 19 20] │ [21 22 23] │ [24 25 26]]] ↓