我希望有一个条件lambda
函数,其中条件检查应用于elemt-by-elemnent。我有以下代码:
p = np.arange(0,1,0.01)
Kl = lambda p: p + 1 if p>0.5 else p-1
K = Kl(p)
产生错误:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
为什么不能以这种方式使用lambda函数?有人可以提出正确的方法来实现这一目标吗?感谢。
答案 0 :(得分:1)
使用np.where()
In [5]: import numpy as np
In [6]: p = np.arange(0, 1, 0.1)
In [7]: l = lambda x: np.where(x>0.5, x+1, x-1)
In [8]: l(p)
Out[8]: array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, 1.6, 1.7, 1.8, 1.9])
使用矢量化表达式比使用listy表达式更快,特别是如果涉及的数组的维度很大。在下文中,对于100万件物品,np.where(…)
比list(map(…))
快〜70倍,而100件物品的优势则要小得多......
In [14]: p = np.arange(0, 1, 0.000001)
In [15]: K0 = lambda p: np.where(p>0.5, p+1, p-1)
In [16]: K1 = lambda p: p + 1 if p>0.5 else p-1
In [17]: %timeit _ = K0(p)
100 loops, best of 3: 8.1 ms per loop
In [18]: %timeit _ = list(map(K1, p))
1 loop, best of 3: 557 ms per loop
In [19]: p = np.arange(0, 1, 0.01)
In [20]: %timeit _ = K0(p)
The slowest run took 9.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 6.99 µs per loop
In [21]: %timeit _ = list(map(K1, p))
10000 loops, best of 3: 58.5 µs per loop