如何从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])。
如何从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])。
当前回答
如果没有想要删除的元素的索引,可以使用numpy提供的in1d函数。
如果一个一维数组的元素也存在于另一个数组中,则该函数返回True。要删除元素,只需对该函数返回的值求负即可。
注意,这个方法保持原始数组的顺序。
In [1]: import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
rm = np.array([3, 4, 7])
# np.in1d return true if the element of `a` is in `rm`
idx = np.in1d(a, rm)
idx
Out[1]: array([False, False, True, True, False, False, True, False, False])
In [2]: # Since we want the opposite of what `in1d` gives us,
# you just have to negate the returned value
a[~idx]
Out[2]: 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副本。请注意, 删除不会发生在原地……”
如果我发布的代码有输出,它是运行代码的结果。
如果不知道索引,就不能使用logical_and
x = 10*np.random.randn(1,100)
low = 5
high = 27
x[0,np.logical_and(x[0,:]>low,x[0,:]<high)]
如果你不知道指数,你可以这样做:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
values = [3, 4, 7]
mask = np.isin(arr, values)
arr = np.delete(arr, mask)
这个带mask的语法在1.19中引入。
你也可以使用集合:
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]
列表理解也是一种有趣的方法。
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = np.array([2, 3, 6]) #index is changed to an array.
out = [val for i, val in enumerate(a) if all(i != index)]
>>> [1, 2, 5, 6, 8, 9]