This question is very similar to a lot of questions related with the warning RuntimeWarning: invalid value encountered in greater/less/etc
However, I couldn't find a solution for my particular problem, and I think there should be one.
So, I have a numpy.ndarray similar to this one:
array([[ nan, 1., nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
...,
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan]])
I want to calculate array > 0.5, which gives exactly the result I want, but with the warning for being comparing with nan:
__main__:1: RuntimeWarning: invalid value encountered in greater
Out[68]:
array([[False, True, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
...,
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]], dtype=bool)
I basically want to calculate array > 0.5, but without the warning showing up.
My restrictions:
- I do NOT want to just suppress the warning with
with np.errstate(invalid='ignore'): - I need to maintain the original array, thus I cannot change it.
I have come up with a simple solution:
- Change the
nanin the original matrix (array[np.isnan(array)] = -np.inf), recovering it back after I do my comparison (array[array == -np.inf] = np.nan)
But I think it is just a waste of time all these calculations when (I think) it should exist a direct way to do this at once. I have been exploring the numpy.ma module and the numpy.where function, but I couldn't find this "direct" solution which I want.
Any thoughts on this?