如何使用数组对数组进行切片索引?

2024-04-26 21:00:39 发布

您现在位置:Python中文网/ 问答频道 /正文

也许这件事在别的地方被提出来了,但我还没有找到。 假设我们有一个numpy数组:

a = np.arange(100).reshape(10,10)
b = np.zeros(a.shape)
start = np.array([1,4,7])   # can be arbitrary but valid values
end = np.array([3,6,9])     # can be arbitrary but valid values

startend都有有效值,因此每个切片对a也是有效的。 我想将a中的子数组值复制到b中的相应点:

^{pr2}$

此语法不起作用,但等效于:

b[:, start[0]:end[0]] = a[:, start[0]:end[0]]
b[:, start[1]:end[1]] = a[:, start[1]:end[1]]
b[:, start[2]:end[2]] = a[:, start[2]:end[2]]

我想知道是否有更好的方法来代替在startend数组上显式的for循环。在

谢谢!在


Tags: numpy地方np数组bearraystartcan
1条回答
网友
1楼 · 发布于 2024-04-26 21:00:39

我们可以使用^{}创建一个要编辑的位置的掩码,其中包含两组与startend数组的比较,然后简单地用boolean-indexing为矢量化解决方案赋值-

# Range array for the length of columns
r = np.arange(b.shape[1])

# Broadcasting magic to give us the mask of places
mask = (start[:,None] <= r) & (end[:,None] >= r)

# Boolean-index to select and assign 
b[:len(mask)][mask] = a[:len(mask)][mask]

样本运行-

^{pr2}$

相关问题 更多 >