Created
August 1, 2017 13:47
-
-
Save dbaston/b41c3fa8c02ac151e52e132509c89b4c to your computer and use it in GitHub Desktop.
mask-aware numpy vectorize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def masked_vectorize(fn): | |
vectorized = np.vectorize(fn) | |
def ret(*args, **kwargs): | |
# In theory, it should be possible to replace this with | |
# np.ma.logical_or.reduce([a.mask for a in args]) | |
# In practice, it seems to generate an error when the | |
# internal storage of the arguments is different | |
# ValueError: setting an array element with a sequence. | |
masked_args = [arg for arg in args if isinstance(arg, np.ma.core.MaskedArray)] | |
if not masked_args: | |
return vectorized(*args, **kwargs) | |
else: | |
combined_mask = masked_args[0].mask | |
for arg in masked_args[1:]: | |
combined_mask = combined_mask | arg.mask | |
vals = np.ma.where(combined_mask, | |
np.ma.masked, | |
vectorized(*args, **kwargs)) | |
return vals | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, but I am looking for a version that does not call func on masked values (because that raises an exception).