如何从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])。


当前回答

你也可以使用集合:

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]

其他回答

有一个numpy内置函数可以帮助实现这一点。

import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])

使用numpy.delete() -返回一个新数组,其子数组沿已删除的轴

numpy.delete(a, index)

关于你的具体问题:

import numpy as np

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

new_a = np.delete(a, index)

print(new_a) #Prints `[1, 2, 5, 6, 8, 9]`

注意,numpy.delete()返回一个新数组,因为数组标量是不可变的,类似于Python中的字符串,所以每次对它进行更改时,都会创建一个新对象。也就是说,引用delete()文档:

"删除了由obj指定的元素的arr副本。请注意, 删除不会发生在原地……”

如果我发布的代码有输出,它是运行代码的结果。

如果我们知道要删除的元素的索引,使用np.delete是最快的方法。但是,为了完整起见,让我添加另一种“删除”数组元素的方法,使用在np.isin的帮助下创建的布尔掩码。该方法允许我们通过直接指定或通过索引来删除元素:

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

按指数移除:

indices_to_remove = [2, 3, 6]
a = a[~np.isin(np.arange(a.size), indices_to_remove)]

按元素删除(不要忘记重新创建原来的a,因为它在前一行中被重写了):

elements_to_remove = a[indices_to_remove]  # [3, 4, 7]
a = a[~np.isin(a, elements_to_remove)]

Numpy数组是不可变的,这意味着从技术上讲不能从其中删除项。然而,你可以构造一个没有你不想要的值的新数组,就像这样:

b = np.delete(a, [2,3,6])

你也可以使用集合:

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]