屏蔽数组中的特定值 [英] Mask out specific values from an array

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

问题描述

示例:

我有一个数组:

array([[1, 2, 0, 3, 4],
       [0, 4, 2, 1, 3],
       [4, 3, 2, 0, 1],
       [4, 2, 3, 0, 1],
       [1, 0, 2, 3, 4],
       [4, 3, 2, 0, 1]], dtype=int64)

我有一组坏"值(长度可变,顺序无关紧要):

I have a set (variable length, order doesn't matter) of "bad" values:

{2, 3}

我想返回隐藏这些值的遮罩:

I want to return the mask that hides these values:

array([[False,  True, False,  True, False],
       [False, False,  True, False,  True],
       [False,  True,  True, False, False],
       [False,  True,  True, False, False],
       [False, False,  True,  True, False],
       [False,  True,  True, False, False]], dtype=bool)

在NumPy中最简单的方法是什么?

What's the simplest way to do this in NumPy?

推荐答案

使用

Use np.in1d that gives us a flattened mask of such matching occurrences and then reshape back to input array shape for the desired output, like so -

np.in1d(a,[2,3]).reshape(a.shape)

请注意,我们需要将要搜索的数字作为列表或数组输入.

Note that we need to feed in the numbers to be searched as a list or an array.

样品运行-

In [5]: a
Out[5]: 
array([[1, 2, 0, 3, 4],
       [0, 4, 2, 1, 3],
       [4, 3, 2, 0, 1],
       [4, 2, 3, 0, 1],
       [1, 0, 2, 3, 4],
       [4, 3, 2, 0, 1]])

In [6]: np.in1d(a,[2,3]).reshape(a.shape)
Out[6]: 
array([[False,  True, False,  True, False],
       [False, False,  True, False,  True],
       [False,  True,  True, False, False],
       [False,  True,  True, False, False],
       [False, False,  True,  True, False],
       [False,  True,  True, False, False]], dtype=bool)

2018年版:numpy.isin

使用内置的NumPy (在

2018 Edition : numpy.isin

Use NumPy built-in np.isin (introduced in 1.13.0) that keeps the shape and hence doesn't require us to reshape afterwards -

In [153]: np.isin(a,[2,3])
Out[153]: 
array([[False,  True, False,  True, False],
       [False, False,  True, False,  True],
       [False,  True,  True, False, False],
       [False,  True,  True, False, False],
       [False, False,  True,  True, False],
       [False,  True,  True, False, False]])

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

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