代码之家  ›  专栏  ›  技术社区  ›  Igor Rivin

numpy广播用户功能

  •  1
  • Igor Rivin  · 技术社区  · 6 年前

    numpy ,如果 a 是一个数组,那么,类似 np.sin(a) sin 在所有的ndarray条目中。如果我需要定义自己的函数(举个愚蠢的例子, f(x) = sin(x) if x<1 else cos(x) )有广播行为吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Hans Musgrave    6 年前

    你可以定义你自己的函数 f = lambda x: sin(x) if x<1 else cos(x) f_broadcasting = np.vectorize(f) .

        2
  •  2
  •   sacuL    6 年前

    np.where

    np.where(a<1,np.cos(a), np.sin(a))
    

    例子:

    a = [-1,1,2,-2]
    
    >>> np.where(a<1,np.cos(a), np.sin(a))
    array([-0.84147098,  0.84147098,  0.90929743, -0.90929743])
    

    如果您有多个条件,请使用 np.select