numpy索引切片,无

use*_*757 8 python numpy

通过一个滑动窗口示例为numpy.试图了解,Nonestart_idx = np.arange(B[0])[:,None]

foo = np.arange(10)
print foo
print foo[:]
print foo[:,]
print foo[:,None]
Run Code Online (Sandbox Code Playgroud)

的效果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]]
Run Code Online (Sandbox Code Playgroud)

但我不完全确定.我无法找到解释第二个参数(None)的内容的文档.这也是google的一个难点.该numpy的阵列文档让我觉得它是与先进的索引,但我不能肯定不够.

piR*_*red 17

foo[:, None]将1维数组扩展foo到第二维.实际上,numpy使用别名np.newaxis来执行此操作.

考虑 foo

foo = np.array([1, 2])
print(foo)

[1 2]
Run Code Online (Sandbox Code Playgroud)

一维阵列具有局限性.例如,什么是转置?

print(foo.T)

[1 2]
Run Code Online (Sandbox Code Playgroud)

与数组本身相同

print(foo.T == foo)

[ True True]
Run Code Online (Sandbox Code Playgroud)

这种限制具有许多含义,foo在更高维度的背景下考虑变得有用.numpy用途np.newaxis

print(foo[np.newaxis, :])

[[1 2]]
Run Code Online (Sandbox Code Playgroud)

但这np.newaxis只是语法糖None

np.newaxis is None

True
Run Code Online (Sandbox Code Playgroud)

所以,我们经常使用None它,因为它的字符越少,意味着同样的东西

print(foo[None, :])

[[1 2]]
Run Code Online (Sandbox Code Playgroud)

好的,让我们看看我们还能做些什么.注意我None在第一个位置使用了示例,而OP使用第二个位置.此位置指定扩展哪个维度.我们可以采取进一步的措施.让这些例子有助于解释

print(foo[None, :])  # same as foo.reshape(1, 2)

[[1 2]]
Run Code Online (Sandbox Code Playgroud)
print(foo[:, None])  # same as foo.reshape(2, 1)

[[1]
 [2]]
Run Code Online (Sandbox Code Playgroud)
print(foo[None, None, :])  # same as foo.reshape(1, 1, 2) 

[[[1 2]]]
Run Code Online (Sandbox Code Playgroud)
print(foo[None, :, None])  # same as foo.reshape(1, 2, 1)

[[[1]
  [2]]]
Run Code Online (Sandbox Code Playgroud)
print(foo[:, None, None])  # same as foo.reshape(2, 1, 1)

[[[1]]

 [[2]]]
Run Code Online (Sandbox Code Playgroud)

请记住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]]] ?
Run Code Online (Sandbox Code Playgroud)