Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

python - numpy index slice with 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]

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

The same as the array itself

print(foo.T == foo)

[ True True]

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

But this np.newaxis is just syntactic sugar for None

np.newaxis is None

True

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

print(foo[None, :])

[[1 2]]

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...