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.
You are trying to apply your lambda function to the whole array, but what you want is to apply it to every element. There are more numpy-y solutions to this. Let your array be
a
andnumpy
be imported asnp
. You could use fancy indexing:or even better
np.where
:The explanation is in the docs of
where
:Why not using directly a comprehension list:
Data
x > 0
is evaluated for your numpy array as a whole, returning another array of booleans. However, theif
statement evaluates the whole array as a single operation.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 vectorizedif-else
statementE.g.