Nip*_*per 5 python arrays lambda runtime-error numpy
目前我在处理 numpy.array - 4x1 - 即时遇到错误
[[-1.96113883]
[-3.46144244]
[ 5.075857 ]
[ 1.77550086]]
Run Code Online (Sandbox Code Playgroud)
与 lambda 函数f = lambda x: x if (x > 0) else (x * 0.01)。
错误是ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()。
我在 stackoverflow.com 上搜索了不同的主题,但没有找到任何令人满意的问题解释和适合我的案例(许多对运算符and、矢量化代码等的不清楚引用)。
处理数组后我期望得到一个与输入维度相同的数组,并且根据函数修改每个单个值,例如:
[[-0.0196113883]
[-0.0346144244]
[ 5.075857 ]
[ 1.77550086]]
Run Code Online (Sandbox Code Playgroud)
最后,有人可以为我提供解决方案并解释为什么会出现此错误。谢谢你的建议。
x > 0对您的 numpy 数组作为一个整体进行评估,返回另一个布尔值数组。但是,该if语句将整个数组作为单个操作进行计算。
arr = np.array([[-1.96113883],
[-3.46144244],
[ 5.075857 ],
[ 1.77550086]])
print arr > 0
[[False]
[False]
[ True]
[ True]]
Run Code Online (Sandbox Code Playgroud)
正如错误消息中所述,布尔数组的真值不明确。
相反,正如 ajcr 在评论中指出的那样,您应该使用np.where向量化if-else语句
例如
np.where(arr > 0, arr, arr*0.01)
array([[-0.01961139],
[-0.03461442],
[ 5.075857 ],
[ 1.77550086]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1951 次 |
| 最近记录: |