“在"numpy 数组的运算符? [英] "In" operator for numpy arrays?

查看:25
本文介绍了“在"numpy 数组的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对 numpy 数组进行in"操作?(如果给定的 numpy 数组中存在元素,则返回 True)

How can I do the "in" operation on a numpy array? (Return True if an element is present in the given numpy array)

对于字符串、列表和字典,其功能易于理解.

For strings, lists and dictionaries, the functionality is intuitive to understand.

这是我将其应用于 numpy 数组时得到的

Here's what I got when I applied that on a numpy array

a
array([[[2, 3, 0],
    [1, 0, 1]],

   [[3, 2, 0],
    [0, 1, 1]],

   [[2, 2, 0],
    [1, 1, 1]],

   [[1, 3, 0],
    [2, 0, 1]],

   [[3, 1, 0],
    [0, 2, 1]]])

b = [[3, 2, 0],
    [0, 1, 1]]

b in a
True
#Aligned with the expectation

c = [[300, 200, 0],
    [0, 100, 100]]

c in a
True
#Not quite what I expected

推荐答案

您可以比较 equality 的输入数组,这将执行 broadcasteda 中所有元素在最后每个位置的比较两个轴针对第二个数组中相应位置的元素.这将产生一个布尔匹配数组,我们在其中检查 ALL 匹配最后两个轴,最后检查 ANY 匹配,就像这样 -

You could compare the input arrays for equality, which will perform broadcasted comparisons across all elements in a at each position in the last two axes against elements at corresponding positions in the second array. This will result in a boolean array of matches, in which we check for ALL matches across the last two axes and finally check for ANY match, like so -

((a==b).all(axis=(1,2))).any()

样品运行

1) 输入:

In [68]: a
Out[68]: 
array([[[2, 3, 0],
        [1, 0, 1]],

       [[3, 2, 0],
        [0, 1, 1]],

       [[2, 2, 0],
        [1, 1, 1]],

       [[1, 3, 0],
        [2, 0, 1]],

       [[3, 1, 0],
        [0, 2, 1]]])

In [69]: b
Out[69]: 
array([[3, 2, 0],
       [0, 1, 1]])

2) 广播元素比较:

In [70]: a==b
Out[70]: 
array([[[False, False,  True],
        [False, False,  True]],

       [[ True,  True,  True],
        [ True,  True,  True]],

       [[False,  True,  True],
        [False,  True,  True]],

       [[False, False,  True],
        [False, False,  True]],

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

3) ALL 跨越最后两个轴匹配,最后 ANY 匹配:

3) ALL match across last two axes and finally ANY match :

In [71]: (a==b).all(axis=(1,2))
Out[71]: array([False,  True, False, False, False], dtype=bool)

In [72]: ((a==b).all(axis=(1,2))).any()
Out[72]: True

a 中的 c 执行类似的步骤 -

Following similar steps for c in a -

In [73]: c
Out[73]: 
array([[300, 200,   0],
       [  0, 100, 100]])

In [74]: ((a==c).all(axis=(1,2))).any()
Out[74]: False

这篇关于“在"numpy 数组的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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