python - 如何删除numpy数组中的特定元素

如何从 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/

相关文章:

linux - 如何提取 rpm 的内容?

Python Infinity - 有什么注意事项吗?

linux - 使用 Bash 自动将最后一个命令的输出捕获到变量中?

python - 自定义类型的对象作为字典键

linux - 如何强制从另一个 SSH session 中分离 screen ?

python - 编码/解码有什么区别?

python - ValueError : The truth value of an array

linux - 比较 bash 中的整数,需要一元运算符

linux - 使用 tar、gz、zip 或 bzip2 拆分文件

c - 编写程序以处理导致 Linux 上丢失写入的 I/O 错误