I was trying to debug some code today and found that I had a nan
value propagating
through some calculations, causing very weird behavior. I figured there must be a
quick way to check numpy arrays for nan values. We can use the numpy function isnan
:
Here we can see that isnan
returns a boolean array in the same shape as the input data,
with a value of True
indicating that the value at that point in the array is a nan
. We
can use these booleans to slice the arrays to access the nans:
But that’s not particularly useful, so lets invert the logic using ~
so we can get all of the
non nan
data:
This performs a unary bitwise inversion on each element in our array, swapping True
to False
and False
to True
. Finally,
if we are not interested in where the nans are, but just want to know if they are there
or not, we can use any() to return a boolean if any value in the array is true:
Or if we wanted to check that every value in an array was true, for example if we had all nans, we can use all():
Or to check that every value is not a nan
we can use all()
and ~
together: