Reputation: 918
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]))
Upvotes: 2
Views: 2678
Reputation:
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
--
--
--
Upvotes: 0
Reputation: 934
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 -- -- --]
>>>
Upvotes: 0
Reputation: 531245
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]))
Upvotes: 2