如何移除numpy数组中的特定元素

2024-03-28 15:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: importnumpy元素indexasnp数组array
3条回答

Numpy数组是immutable,这意味着技术上不能从中删除项。但是,您可以在不需要值的情况下构造一个数组,如下所示:

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

有一个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()-返回一个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..."

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

相关问题 更多 >