如何从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]
)。
过滤掉您不需要的部分:
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]]
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]
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中引入的。