簡體   English   中英

numpy最多需要3個參數-一種解決方法?

[英]numpy where takes at most 3 arguments - a way around this?

假設我有以下代碼:

import numpy as np

def myf(c):
    return c*11

def method_A(c):
    return c*999

def method_B(c):
    return c*55

minimum = 30
maximum = 100
the_method = 'A'

b = np.array([1, 20, 35, 3, 45, 52, 78, 101, 127, 135])

我想在這里使用numpy來滿足一些條件。

就像是:

b = np.where( np.logical_or(b < minimum , b > maximum) , b, 
             (if the_method == 'A': method_A(b)) ,
             (if the_method == 'B': method_B(b)))

如果滿足條件b < min or b > maxif the_method is A , call method A b中的每個元素保持原樣,否則, if the_method is A , call method A if method is B, call method B

因此,我嘗試:

b = np.where( np.logical_or(b < minimum , b > maximum) , b, 
             (np.where(the_method == 'A',method_A(b),b)),
             (np.where(the_method == 'B',method_B(b),b))
            )

這給了我function takes at most 3 arguments (4 given)因為np.where不能接受超過3個參數。

有辦法解決我的問題嗎?

the_method是標量而不是數組,因此您不需要內部np.where s:

if the_method == 'A':
    which_method = method_A 
elif the_method == 'B':
    which_method = method_B 
else:
    raise ValueError

b = np.where(
    (b < minimum) | (b > maximum),
     b, 
     which_method(b)
)

實際上,如果在這兩種方法中都插入了print件,則與使用np.where ,它們都會運行。

如果您真的想在一個表達式中得到它:

def _raise(x): raise x

b = np.where(
    (b < minimum) | (b > maximum),
     b, 
     (
         method_A if the_method == 'A' else
         method_B if the_method == 'B' else
         _raise(ValueError)
     )(b)
)

您的括號不平衡,您需要在內部條件中附加括號:

In [33]:
b = np.where( np.logical_or(b < minimum , b > maximum) , b,
             ((np.where(apply_method == 'A',method_A(b),
             (np.where(apply_method == 'B',method_B(b),None))
            ))))
b

Out[33]:
array([1, 20, 35000, 3, 45000, 52000, 78000, 101, 127, 135], dtype=object)

您最初的嘗試:

b = np.where( np.logical_or(b < minimum , b > maximum) , b, 
             (np.where(the_method == 'A',method_A(b),b)),
             (np.where(the_method == 'B',method_B(b),b))
            )

其他條件下需要的括號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM