在有条件的数组上操作



考虑以下代码,

import numpy as np
xx = np.asarray([1,0,1])
def ff(x):
return np.sin(x)/x
# this throws an error because of division by zero
# C:UsersUserAppDataLocalTemp/ipykernel_2272/525615690.py:4: 
# RuntimeWarning: invalid value encountered in true_divide
# return np.sin(x)/x
yy = ff(xx)
# to avoid the error, I did the following
def ff_smart(x):
if (x==0):
# because sin(x)/x = 1 as x->0
return 1
else:
return np.sin(x)/x
# but then I cannot do
# yy_smart = ff_smart(xx)
# because of ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
# I therefore have to do:
*yy_smart, = map(ff_smart,xx)
yy_smart = np.asarray(yy_smart)

有没有一种方法(一些numpy魔术(可以写ff_smart,这样我就可以在不使用map的情况下调用它,而ff_smart仍然可以在标量(非numpy数组(上操作。我希望避免在ff_smart中进行类型检查。

你可以做:

yy = [np.sin(x)/x if x != 0 else 1 for x in xx]

如果你想使用numpy的力量,另一个不同的答案,仍然有用的是使用掩码数组:

# initialize x
x = np.array([2, 3, 1, 0, 2])
# compute the masked array of x, masking out 0s
masked_x = np.ma.array(x, mask= x == 0, dtype=x.dtype)
# perform operation only on non-zero values
y = np.sin(masked_x) / masked_x
# get the value back, filling the masked out values with 1s.
y = np.ma.filled(y, fill_value=1)

对于您所描述的条件运算,numpy具有numpy where函数。

你可以做

np.where(x==0, 1, np.sin(x)/x)

最新更新