在numpy中使用蒙面数组进行索引 [英] Indexing with Masked Arrays in numpy

查看:332
本文介绍了在numpy中使用蒙面数组进行索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码尝试在另一个指定的索引处查找数组的内容,这可能指定超出前一个数组范围的索引。

I have a bit of code that attempts to find the contents of an array at indices specified by another, that may specify indices that are out of range of the former array.

input = np.arange(0, 5)
indices = np.array([0, 1, 2, 99])

我想要做的是:
打印输入[indices]
并获得
[0 1 2]

What I want to do is this: print input[indices] and get [0 1 2]

但这会产生异常(如预期):

But this yields an exception (as expected):

IndexError: index 99 out of bounds 0<=index<5

所以我想我可以使用掩盖数组以隐藏越界索引:

So I thought I could use masked arrays to hide the out of bounds indices:

indices = np.ma.masked_greater_equal(indices, 5)

但仍然:

>print input[indices]
IndexError: index 99 out of bounds 0<=index<5

即使:

>np.max(indices)
2

所以我必须首先填充蒙面数组,这很烦人,因为我不知道我可以使用什么填充值来不为超出范围的那些选择任何索引:

So I'm having to fill the masked array first, which is annoying, since I don't know what fill value I could use to not select any indices for those that are out of range:


打印输入[np.ma.filled(indices,0)]

print input[np.ma.filled(indices, 0)]



[0 1 2 0]

所以我的问题是:怎么能你有效地使用numpy来安全地从数组中选择索引而不超出输入数组的边界吗?

So my question is: how can you use numpy efficiently to select indices safely from an array without overstepping the bounds of the input array?

推荐答案

不使用掩码数组,您可以删除大于或等于5的索引,如下所示:

Without using masked arrays, you could remove the indices greater or equal to 5 like this:

print input[indices[indices<5]]

编辑:请注意,如果您还想丢弃负指数,可以写下:

note that if you also wanted to discard negative indices, you could write:

print input[indices[(0 <= indices) & (indices < 5)]]

这篇关于在numpy中使用蒙面数组进行索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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