如何从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])。
当前回答
过滤不需要的部分:
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]]
其他回答
Numpy数组是不可变的,这意味着从技术上讲不能从其中删除项。然而,你可以构造一个没有你不想要的值的新数组,就像这样:
b = np.delete(a, [2,3,6])
删除特定索引(我从矩阵中删除了16和21)
import numpy as np
mat = np.arange(12,26)
a = [4,9]
del_map = np.delete(mat, a)
del_map.reshape(3,4)
输出:
array([[12, 13, 14, 15],
[17, 18, 19, 20],
[22, 23, 24, 25]])
列表理解也是一种有趣的方法。
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]
按值删除:
modified_array = np.delete(original_array, np.where(original_array == value_to_delete))
你也可以使用集合:
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]