2

Is there a reasonable way to get the following done on one line? I'd really like to avoid creating a temporary variable or a separate function.

import numpy as np
x = np.array([1,2,3,4,5])
x = np.ma.masked_where(x>2, x)

I tried

x = map(lambda x: np.ma.masked_where(x>2, x), np.array([1,2,3,4,5]))

but the map object is not what I want? I can of course define separate fuction, which avoids assigning variable:

masker = lambda x: np.ma.masked_where(x>2, x)
x = masker(np.array([1,2,3,4,5]))
4
  • In your second "attempt", you would still be creating the intermediate array, you just aren't assigning it. I'm confused why the first approach isn't what you want Commented Jul 24, 2019 at 17:02
  • Why this need for a one-liner? Commented Jul 24, 2019 at 17:02
  • I understand I cannot avoid creating an intermediate array, just want to avoid assigning it. Why, just trying to look for ways to be more functional with numpy. Commented Jul 24, 2019 at 17:10
  • The assignment of the intermediate array causes absolutely no problems, because you immediately reassign the same variable with the final result. Commented Jul 24, 2019 at 17:16

3 Answers 3

2

You don't need map at all, just an anonymous function. All you will do is replace the initial assignment to x with a parameter binding in a function call.

import numpy as np
# x = np.array([1,2,3,4,5])
# x = np.ma.masked_where(x>2, x)

x = (lambda x: np.ma.masked_where(x>2, x))(np.array([1,2,3,4,5]))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I guess that's what I was looking for, but couldn't figure out the syntax.
0

This works great for me and is one liner:

>>> x = (lambda y: np.ma.masked_where(y>2, y))(np.array([1,2,3,4,5]))
>>> print (x)
[1 2 -- -- --]
>>>

2 Comments

How is this different from chepner's answer? :)
It is not. I didn't refresh the page while testing on my computer and posting the answer.
0

Here is a way to do this with map:

import numpy as np

x = map(
    np.ma.masked_where, 
    *(np.array([1,2,3,4,5])>2, np.array([1,2,3,4,5]))
)

Map returns an iterable, so to review the masking, go like:

>>> for item in x:
...     print(item)
... 
1
2
--
--
--

1 Comment

Interesting, but I guess iteration over individual elements is not what one usually does with numpy arrays.

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.