Ambiguous Evaluation of Lambda Expression on Array

Posted by Joe on Stack Overflow See other posts from Stack Overflow or by Joe
Published on 2012-11-23T22:57:11Z Indexed on 2012/11/23 23:03 UTC
Read the original article Hit count: 235

Filed under:
|
|

I would like to use a lambda that adds one to x if x is equal to zero. I have tried the following expressions:

t = map(lambda x: x+1 if x==0 else x, numpy.array)
t = map(lambda x: x==0 and x+1 or x, numpy.array)
t = numpy.apply_along_axis(lambda x: x+1 if x==0 else x, 0, numpy.array)

Each of these expressions returns the following error:

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

My understanding of map() and numpy.apply_along_axis() was that it would take some function and apply it to each value of an array. From the error it seems that the the lambda is being evaluated as x=array, not some value in array. What am I doing wrong?

I know that I could write a function to accomplish this but I want to become more familiar with the functional programming aspects of python.

© Stack Overflow or respective owner

Related posts about python

Related posts about numpy