Python与numpy:如何根据特定索引从二维数组的每一行中删除元素

bra*_*ess 5 python numpy

假设我有一个大小为 20 x 10 的二维 numpy 数组 A。

我还有一个长度为 20 的数组 del_ind。

我想根据 del_ind 从 A 的每一行中删除一个元素,以获得大小为 20 x 9 的结果数组。

我怎样才能做到这一点?

我使用指定的 axis = 1 查看了 np.delete ,但这只会删除每行同一位置的元素。

谢谢您的帮助

wim*_*wim 5

您可能需要构建一个新数组。

幸运的是,您可以使用花哨的索引来避免此任务的 python 循环:

h, w = 20, 10
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)
Run Code Online (Sandbox Code Playgroud)

使用较小数据集的演示:

>>> h, w = 5, 4
>>> %paste
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)

## -- End pasted text --
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> del_ind
array([2, 2, 1, 1, 0])
>>> A_
array([[ 0,  1,  3],
       [ 4,  5,  7],
       [ 8, 10, 11],
       [12, 14, 15],
       [17, 18, 19]])
Run Code Online (Sandbox Code Playgroud)