在什么样的具体情况下,np.piecewise
会比np.where
更方便(不太详细)或计算上比使用np.where
更有效吗?我在遇到这种情况时遇到了问题,而且我似乎碰到了经常用where
进行评估的分段函数。NumPy分段与NumPy其中
np.piecewise
似乎更加详细不论件数:
import numpy as np
b = np.arange(10, 20, dtype=np.float)
# 2 pieces - piecewise is more verbose
a = np.piecewise(b, [b<14, b>=14], [lambda x: x**2, lambda x: x/2])
c = np.where(b>=14, b/2, b ** 2)
print(np.array_equal(a, c))
True
# 3 pieces - piecewise still more verbose (won't it always be?)
d = np.piecewise(b, [b<11, np.logical_and(b>=11, b<14), b>=14],
[1, lambda x: x**2, lambda x: x/2])
e = np.where(b>=14, b/2, np.where(b>=11, b**2, 1))
print(np.array_equal(d, e))
True
这也是显著慢:
from timeit import timer
# variables above redefined as callables with no args
print('times:\n a: %d, c: %d, d: %d, e: %d'
% (timeit(a), timeit(c), timeit(d), timeit(e)))
times:
a: 17, c: 4, d: 21, e: 7