无的numpy索引切片 [英] numpy index slice with None

查看:105
本文介绍了无的numpy索引切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Working through a sliding-window example for numpy. Was trying to understand the ,None of start_idx = np.arange(B[0])[:,None]

foo = np.arange(10)
print foo
print foo[:]
print foo[:,]
print foo[:,None]

None的作用似乎是转置数组.

The effect of the None seems to be to transpose the array.

[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数组文档使我认为它与高级功能有关索引,但我不确定.

But I'm not totally sure. I haven't been able to find the documentation that explains what the second parameter (None) does. It's a hard fragment to google for, too. The numpy array docs makes me think it has something to do with advanced indexing, but I'm not sure enough.

推荐答案

foo[:, None]将一维数组foo扩展到第二维.实际上,numpy使用别名np.newaxis来做到这一点.

foo[:, None] extends the 1 dimensional array foo into the second dimension. In fact, numpy uses the alias np.newaxis to do this.

考虑foo

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

[1 2]

一维数组有局限性.例如,什么是移调?

A one dimensional array has limitations. For example, what's the transpose?

print(foo.T)

[1 2]

与数组本身相同

print(foo.T == foo)

[ True True]

此限制有很多含义,在更高维度的上下文中考虑foo变得很有用. numpy使用np.newaxis

This limitation has many implications and it becomes useful to consider foo in higher dimensional context. numpy uses np.newaxis

print(foo[np.newaxis, :])

[[1 2]]

但这np.newaxis只是None

np.newaxis is None

True

因此,通常我们使用None代替,因为它的字符更少,含义相同.

So, often we use None instead because it's less characters and means the same thing

print(foo[None, :])

[[1 2]]


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


Ok, let's see what else we could've done. Notice I used the example with None in the first position while OP use the second position. This position specifies which dimension is extended. And we could've taken that further. Let these examples help explain

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打印数组时,哪个维度是哪个


Keep in mind which dimension is which when numpy prints the array

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]]] ↓

这篇关于无的numpy索引切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆