获取一个复杂的if语句来处理数组?python

获取一个复杂的if语句来处理数组?python,python,arrays,if-statement,numpy,function,Python,Arrays,If Statement,Numpy,Function,我想这样做: def fun(a,b,c): if (a<b**2) & (a<b*c): result = a/math.pi elif (a<b**2) & (a>=b*c): result = b*2/math.pi elif (a>=b**2) & (a<b*c): result = c*exp(1) elif (a>=b**2) &

我想这样做:

def fun(a,b,c):
    if (a<b**2) & (a<b*c):
        result = a/math.pi
    elif (a<b**2) & (a>=b*c):
        result = b*2/math.pi
    elif (a>=b**2) & (a<b*c):
        result = c*exp(1)
    elif (a>=b**2) & (a>=b*c):
        result = a*b*c*math.pi
    return result, 
def fun(a、b、c):
如果(a=b*c):
结果=a*b*c*math.pi
返回结果,
但是我如何让它与numpy阵列一起工作呢?数组将是a,b和c将是单个数字

我知道numpy.where,但我不知道如何让它像这段代码那样运行。

你可以嵌套一些,广播应该注意将数组和数字平滑地混合:

result = np.where((a < b**2) & (a < b * c), a / np.pi,
                  np.where((a < b**2) & (a >= b * c), b * 2 / np.pi,
                           np.where((a >= b**2) & (a < b*c), c * np.exp(1),
                                    a * b * c * np.pi)))
result=np.其中((a=b*c),b*2/np.pi,
式中((a>=b**2)和(a
例如:

>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> b = 1
>>> c = 2
>>> np.where((a < b**2) & (a < b * c), a / np.pi,
             np.where((a < b**2) & (a >= b * c), b * 2 / np.pi,
                      np.where((a >= b**2) & (a < b*c), c * np.exp(1),
                               a * b * c * np.pi)))
array([[  0.        ,   5.43656366,  12.56637061,  18.84955592],
       [ 25.13274123,  31.41592654,  37.69911184,  43.98229715],
       [ 50.26548246,  56.54866776,  62.83185307,  69.11503838]])
a=np.arange(12)。重塑(3,4) >>>a 数组([[0,1,2,3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>>b=1 >>>c=2 >>>式中((a=b*c),b*2/np.pi, 式中((a>=b**2)和(a
哇,谢谢。我没有意识到我可以把它们那样安顿起来。这当然让我的生活更轻松。出于兴趣,为什么要使用np.pi而不是math.pi?在使用numpy时,我通常不会显式地
导入math
,但是
math.pi
的工作原理应该完全相同。