将lambda表达式应用于数组的元素时发生ValueError [英] ValueError while applying lambda expression to elements of an array

查看:193
本文介绍了将lambda表达式应用于数组的元素时发生ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我在处理numpy.array-4x1时遇到错误-即

  [[-1.96113883] 
[-3.46144244]
[5.075857]
[1.77550086]]

lambda函数 f = lambda x:x if(x> 0)else(x * 0.01)



错误为 ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all()



我在stackoverflow.com上搜索了不同的主题,但我没有找到关于该问题和适合我的情况的任何令人满意的解释(许多不清楚的对运算符的引用,矢量化代码等)。



在处理完数组后,我期望的是一个与输入维度相同的数组,并且每个单个值都根据函数进行了修改,例如:

  [[-0.0196113883] 
[-0.0346144244]
[5.075857]
[1.77550086]]
解决方案

x>对于整个numpy数组,将评估0 ,并返回另一个布尔数组。但是, if 语句将整个数组作为单个操作求值。

  arr = np.array([[-1.96113883],
[-3.46144244],
[ 5.075857],
[1.77550086]])
print arr> 0
[[False]
[False]
[True]
[True]]

如错误消息中所述,布尔数组的真值不明确。



相反,如ajcr在这些注释,您应该使用 np.where 进行矢量化的 if-else 语句



例如

  np.where(arr> 0,arr,arr * 0.01)
数组([[-0.01961139],
[-0.03461442],
[5.075857],
[1.77550086]])


Currently I faced an error while processing a numpy.array - 4x1 - i.e

[[-1.96113883]
 [-3.46144244]
 [ 5.075857  ]
 [ 1.77550086]]

with the lambda function f = lambda x: x if (x > 0) else (x * 0.01).

The error is ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

I searched through the different topics here on stackoverflow.com but I have not find any satisfactory explanation of the problem and a case that suited mine (many unclear references to the and operator, vectorized code etc.).

What I expect after processing the array is an array of the same dimensions of the input one and each single value modified according to the function, which for the example would be:

[[-0.0196113883]
 [-0.0346144244]
 [ 5.075857  ]
 [ 1.77550086]]

Finally, can someone please provide me a solution and the explanation about why this error occurred. Thank you in advice.

解决方案

x > 0 is evaluated for your numpy array as a whole, returning another array of booleans. However, the if statement evaluates the whole array as a single operation.

arr = np.array([[-1.96113883],
                [-3.46144244],
                [ 5.075857  ],
                [ 1.77550086]])
print arr > 0
   [[False]
    [False]
    [ True]
    [ True]]

As stated in the error message, the truth value of an array of booleans is ambigous.

Instead, as noted by ajcr in the comments, you should use np.where for a vectorized if-else statement

E.g.

np.where(arr > 0, arr, arr*0.01)
array([[-0.01961139],
       [-0.03461442],
       [ 5.075857  ],
       [ 1.77550086]])

这篇关于将lambda表达式应用于数组的元素时发生ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆