如何从NumPy数组中获取所有值(不包括特定索引)? [英] How do I get all the values from a NumPy array excluding a certain index?

查看:824
本文介绍了如何从NumPy数组中获取所有值(不包括特定索引)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NumPy数组,我想检索除特定索引之外的所有元素.例如,考虑以下数组

I have a NumPy array, and I want to retrieve all the elements except a certain index. For example, consider the following array

a = [0,1,2,3,4,5,5,6,7,8,9]

如果我指定索引3,则结果应为

If I specify index 3, then the resultant should be

a = [0,1,2,4,5,5,6,7,8,9]

推荐答案

就像调整大小一样,从NumPy数组中删除元素是一个缓慢的操作(特别是对于大型数组,因为它需要分配空间并将所有数据从原始数组复制到新数组). 如果可能的话,应该避免.

Like resizing, removing elements from an NumPy array is a slow operation (especially for large arrays since it requires allocating space and copying all the data from the original array to the new array). It should be avoided if possible.

通常,您可以通过使用屏蔽数组来避免这种情况 a>代替.例如,考虑数组a:

Often you can avoid it by working with a masked array instead. For example, consider the array a:

import numpy as np

a = np.array([0,1,2,3,4,5,5,6,7,8,9])
print(a)
print(a.sum())
# [0 1 2 3 4 5 5 6 7 8 9]
# 50

我们可以在索引3处屏蔽其值,并且可以执行求和,该求和将忽略被屏蔽的元素:

We can mask its value at index 3 and can perform a summation which ignores masked elements:

a = np.ma.array(a, mask=False)
a.mask[3] = True
print(a)
print(a.sum())
# [0 1 2 -- 4 5 5 6 7 8 9]
# 47

屏蔽数组还支持许多操作 >.

如果确实需要,也可以使用compressed方法删除蒙版元素:

If you really need to, it is also possible to remove masked elements using the compressed method:

print(a.compressed())
# [0 1 2 4 5 5 6 7 8 9]

但是如上所述,请尽可能避免.

But as mentioned above, avoid it if possible.

这篇关于如何从NumPy数组中获取所有值(不包括特定索引)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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