如何删除numpy数组中的特定元素 [英] How to remove specific elements in a numpy array

查看:129
本文介绍了如何删除numpy数组中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 numpy 数组中删除某些特定元素?说我有

How can I remove some specific elements from a numpy array? Say I have

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9])

然后我想从 a 中删除 3,4,7.我只知道值的索引 (index=[2,3,6]).

I then want to remove 3,4,7 from a. All I know is the index of the values (index=[2,3,6]).

推荐答案

使用 numpy.delete() - 返回一个 new 数组,其中子数组沿删除的轴被删除

Use numpy.delete() - returns a new array with sub-arrays along an axis deleted

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() 返回一个新数组,因为 数组标量是不可变的,类似于 Python 中的字符串,因此每次对其进行更改时,都会创建一个新对象.即,引用 delete() 文档:

Note that numpy.delete() returns a new array since array scalars are immutable, similar to strings in Python, so each time a change is made to it, a new object is created. I.e., to quote the delete() docs:

删除了 obj 指定的元素的 arr 的副本.注意删除不会就地发生..."

"A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place..."

如果我贴的代码有输出,就是运行代码的结果.

If the code I post has output, it is the result of running the code.

这篇关于如何删除numpy数组中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆