如何在numpy中复制/切片具有高级索引的数组中的特定部分?



我想复制数组的一部分,并将其保存到另一个numpy。问题是,每行元素的数量和位置是变化的。我有两个数组,其中包含我想要获取的行部分的起始索引和结束索引,但切片不会使用数组。

I have try:

import numpy as np
a = np.arange(25).reshape(5,5)
min_idx = np.array(
[0, 1, 2, 1, 0]
)
max_idx = np.array(
[4, 3, 3, 2, 2]
)
b = np.zeros_like(a)
b[:, min_idx:max_idx] = a[:,min_idx:max_idx]

和b:

target_b = np.array([
[0, 1, 2, 3, 4],
[0, 6, 7, 8, 0],
[0, 0, 12, 13, 0],
[0, 16, 17, 0, 0],
[20, 21, 22, 0, 0]
]
)

使用广播和掩码:

c = np.arange(a.shape[1])
m1 = min_idx[:, None] <= c
m2 = max_idx[:, None] >= c
m = m1&m2
b[m] = a[m]

b:

array([[ 0,  1,  2,  3,  4],
[ 0,  6,  7,  8,  0],
[ 0,  0, 12, 13,  0],
[ 0, 16, 17,  0,  0],
[20, 21, 22,  0,  0]])