How to remove nan and inf values from a numpy matrix?
If you don't want to modify the array in place, you can make use of the np.ma
library, and create a masked array:
np.ma.masked_array(output, ~np.isfinite(output)).filled(0)
array([[1. , 0.5 , 1. , 1. , 0. ,
1. ],
[1. , 1. , 0.5 , 1. , 0.46524064,
1. ],
[1. , 1. , 1. , 0. , 1. ,
1. ]])
There is a special function just for that:
numpy.nan_to_num(x_arr, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
You can just replace NaN
and infinite values with the following mask:
output[~np.isfinite(output)] = 0
>>> output
array([[1. , 0.5 , 1. , 1. , 0. ,
1. ],
[1. , 1. , 0.5 , 1. , 0.46524064,
1. ],
[1. , 1. , 1. , 0. , 1. ,
1. ]])