簡體   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