如何在numpy数组中删除特定元素

338

如何从NumPy数组中删除特定元素?假设我有:

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9])

我想从a中删除3,4,7。我知道的是这些值的索引(index=[2,3,6])。

13个回答

1

过滤掉您不需要的部分:

import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
a = a[(a!=3)&(a!=4)&(a!=7)]

如果您有一组要删除的索引列表:

to_be_removed_inds = [2,3,6]
a = np.array([1,2,3,4,5,6,7,8,9])
a = a[[x for x in range(len(a)) if x not in to_be_removed]]

1
您可以使用集合(sets):
a = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
the_index_list = [2, 3, 6]

the_big_set = set(numpy.arange(len(a)))
the_small_set = set(the_index_list)
the_delta_row_list = list(the_big_set - the_small_set)

a = a[the_delta_row_list]

0
如果您现在不知道索引,可以尝试以下方法:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
values = [3, 4, 7]
mask = np.isin(arr, values)
arr = np.delete(arr, mask)

这个带有掩码的语法是在1.19中引入的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接