如何从 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.delete() - 返回一个 new 数组,其中删除了沿轴的子数组
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()
返回一个新数组,因为 array scalars是不可变的,类似于 Python 中的字符串,因此每次对其进行更改时,都会创建一个新对象。即,引用 delete()
docs :
"A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place..."
如果我发布的代码有输出,那是代码运行的结果。
https://stackoverflow.com/questions/10996140/