如何在numpy中表示“:”

Bo *_*Shi 4 python numpy

我想对多维 ndarray 进行切片,但不知道要在哪个维度上进行切片。假设我们有一个形状为 (6,7,8) 的 ndarray A。有时我需要在第一维 A[:,3,4] 上切片,有时在第三维 A[1,2,:] 上切片。

有没有代表“:”的符号?我想用它来生成索引数组。

index=np.zeros(3)
index[0]=np.:
index[1]=3
index[2]=4
A[index]
Run Code Online (Sandbox Code Playgroud)

cel*_*cel 5

:可以通过调用显式创建切片以下slice(None)是一个简短的示例:

import numpy as np
A = np.arange(9).reshape(3, -1)

# extract the 2nd column
A[:, 1]

# equivalently we can do
cslice = slice(None) # represents the colon
A[cslice, 1]
Run Code Online (Sandbox Code Playgroud)