我的代码是:-
import numpy as np
def f(x):
if x<=0.5:
return 0
else:
return 1
X=np.array([0.1,0.2,0.6,0.5,0.01,1])
print(f(X))此代码给出一个错误。
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()但我不知道a.any()或a.all()对我有什么用处。我要输出的是:-
[0,0,1,0,0,1]我可以使用for循环,但是是否有任何快捷语法使我只需一次就可以得到所需的输出?
发布于 2020-08-15 08:26:12
您可以使用vectorize - https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html
In [1]: import numpy as np
In [2]: X=np.array([0.1,0.2,0.6,0.5,0.01,1])
In [3]: f = lambda x: 0 if x<=0.5 else 1
In [4]: func = np.vectorize(f)
In [5]: func(X)
Out[5]: array([0, 0, 1, 0, 0, 1])或
where - https://numpy.org/doc/stable/reference/generated/numpy.where.html
In [7]: np.where(X<=0.5, 0,1)
Out[7]: array([0, 0, 1, 0, 0, 1])https://stackoverflow.com/questions/63423989
复制相似问题