【发布时间】:2020-06-04 17:42:07
【问题描述】:
我有一个二维 numpy 数组,我想修改二维块(如 9x9 数独板上的 3x3 子块)。我不想使用花哨的索引,而是使用内置的slice。有没有办法使这项工作?我在想 stride 参数(slice 的第三个参数)可以用来以某种方式做到这一点,但我不太明白。我的尝试如下。
import numpy as np
# make sample array (dim-1)
x = np.linspace(1, 81, 81).astype(int)
i = slice(0, 3)
print(x[i])
# [1 2 3]
# make sample array (dim-2)
X = x.reshape((9, 9))
假设我想访问X 的前 3 行和前 3 列。我可以用花哨的索引来做到这一点:
print(X[:3, :3])
# [[ 1 2 3]
# [10 11 12]
# [19 20 21]]
尝试使用与 slice 的 dim-1 案例类似的逻辑:
j = np.array([slice(0,3), slice(0,3)]) # wrong way to acccess
print(X[j])
抛出以下错误:
IndexError: arrays used as indices must be of integer (or boolean) type
【问题讨论】:
标签: python-3.x numpy multidimensional-array indexing slice