How can I check if a given value is NaN?
e.g. if (a == np.NaN)
(doesn't work)
Please note that:
- Numpy's
isnan
method throws errors with data types like string - Pandas docs only provide methods to drop rows containing NaNs, or ways to check if/when DataFrame contains NaNs. I'm asking about checking if a specific value is NaN.
- Relevant Stackoverflow questions and Google search results seem to be about checking "if any value is NaN" or "which values in a DataFrame"
There must be a clean way to check if a given value is NaN?
Best Answer
You can use the inate property that
NaN
!=NaN
so
a == a
will returnFalse
ifa
isNaN
This will work even for strings
Example:
This can be done in a vectorised manner:
but you can still use the method
isnull
on the whole series:UPDATE
As noted by @piRSquared if you compare
None==None
this will returnTrue
butpd.isnull
will returnTrue
so depending on whether you want to treatNone
asNaN
you can still use==
for comparison orpd.isnull
if you want to treatNone
asNaN