繁体   English   中英

从 numpy 数组,获取值列表的索引

[英]From numpy array, get indices of values list

像这样:

>> arr = np.array([[0, 50], [100, 150], [200, 250]]) 
>>> values = [100, 200, 300] 

>>> arr in values

预计:

array([[False, False],
       [ True, False],
       [ True, False]])

结果:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我编写了以下代码并且它有效,但是此代码不能接受更改列表长度

(arr==values[0]) | (arr==values[1]) | (arr==values[2])

使用 np.isin:

import numpy as np

arr = np.array([[0, 50], [100, 150], [200, 250]])
values = [100, 200, 300]

np.isin(arr, values)

结果:

array([[False, False],
       [ True, False],
       [ True, False]])

这应该有效,但仅适用于 2 级深度:

import numpy as np


def is_in(arr, values):
    agg = []
    for a in arr:
        if isinstance(a, list):
            result = is_in(a, values)
            agg.append(result)
        else:
            result = np.isin(arr, values)
            return result
    return agg

arr = np.array([[0, 50], [100, 150], [200, 250]])
values = [100, 200, 300]

print(is_in(arr, values))

例如,还将该变量的名称从 values 更改为与 valuess 不同的名称。

if valuess in arr.values :
print(valuess)

或者

使用 lambda 函数。

假设您有一个数组:

nums = [0,1,5]
Check whether 5 is in nums:

(len(filter (lambda x : x == 5, nums)) > 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM