在 numpy ,如果 a 是一个数组,那么,类似 np.sin(a) 拿 sin 在所有的ndarray条目中。如果我需要定义自己的函数(举个愚蠢的例子, f(x) = sin(x) if x<1 else cos(x) )有广播行为吗?
numpy
a
np.sin(a)
sin
f(x) = sin(x) if x<1 else cos(x)
你可以定义你自己的函数 f = lambda x: sin(x) if x<1 else cos(x) f_broadcasting = np.vectorize(f) .
f = lambda x: sin(x) if x<1 else cos(x)
f_broadcasting = np.vectorize(f)
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
np.select