0

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.

6
  • 1
    What is numpy.array? I assume it's not the numpy function of that name? What is the data you're trying to apply this to? Commented Nov 23, 2012 at 23:01
  • 2
    It works for me; for example, map(lambda x: x+1 if x==0 else x, np.array([0, 1, 2, 3])) evaluates to [1, 1, 2, 3], as expected. Please provide a minimal working example that exhibits the behavior you're describing. Commented Nov 23, 2012 at 23:03
  • Is your array multidimensional? Commented Nov 23, 2012 at 23:04
  • On a side note, x+1 if x==0 can be written as 1 if x==0 or 1 if not x. x==0 and x+1 or x I find not very clear. Perhaps the shortest form for it all is x if x else 1. Commented Nov 23, 2012 at 23:09
  • 2
    @Joe: Can you show an actual example with an actual array? Commented Nov 23, 2012 at 23:19

1 Answer 1

8

If you're using numpy, you should be writing vectorised code:

arr + (arr == 0)
Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain this a bit more? I'm not sure what is going on here.
@Joe looping over every element of a large array in Python is slow. Arithmetic, logical and comparison operators on a numpy array are treated elementwise, so this will give you the result in a far more efficient form.
I get the goal of vectorization, I just don't exactly understand how the expression you posted works.
@Joe (arr == 0) gives a boolean array that is True where arr is equal to 0. In arithmetic, True is converted to 1 and False to 0, so this adds 1 where arr is equal to 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.