【发布时间】:2017-06-16 16:10:41
【问题描述】:
假设我有这个代码:
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 where 来满足一些条件。
类似:
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 > max条件,则将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 个参数。
有没有办法解决我的问题?
【问题讨论】:
-
内部
where周围是否需要额外的括号?像这样:In [20]: 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))) ) b Out[20]: array([[ 1, 20, 34965, 3, 44955, 51948, 77922, 101, 127, 135], [ 1, 20, 35, 3, 45, 52, 78, 101, 127, 135]])? -
嗯..是的!我只想要一个数组作为输出,而不是两个。
-
np.where及其三个参数实现 IF-ELSE,而您有两个 IF。所以,我不确定np.where在这里是否是一个不错的选择。 -
@EdChum:嗯,好的!我只是打开括号并使用
((np.where(apply_method == 'A',method_A(b), (np.where(apply_method == 'B',method_B(b),None)),它工作正常!如果你想把它作为答案,谢谢 -
您发布的 sn-p 不起作用,
apply_method未定义