pandas.isnull() (also pd.isna(), in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:

NaN in numeric arrays, None/NaN in object arrays

Quick example:

import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]: 
0    False
1     True
2    False
dtype: bool

The idea of using numpy.nan to represent missing values is something that pandas introduced, which is why pandas has the tools to deal with it.

Datetimes too (if you use pd.NaT you won't need to specify the dtype)

In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')

In [25]: s
Out[25]: 
0   2013-01-01 00:00:00
1                   NaT
2   2013-01-02 09:30:00
dtype: datetime64[ns]``

In [26]: pd.isnull(s)
Out[26]: 
0    False
1     True
2    False
dtype: bool
Answer from Marius on Stack Overflow
🌐
CodeSpeedy
codespeedy.com › home › check if a given string is nan in python
Check if a given string is NaN in Python - CodeSpeedy
March 24, 2022 - Let us define a boolean function isNaN() which returns true if the given argument is a NaN and returns false otherwise. def isNaN(string): return string != string print(isNaN("hello")) print(isNaN(np.nan))
🌐
Python Guides
pythonguides.com › check-if-a-string-is-empty-or-nan-in-python
How To Check If A String Is Empty Or NaN In Python?
March 19, 2025 - Learn how to check if a string is empty or NaN in Python using simple techniques like conditional statements, len(), and libraries like math and pandas.
Top answer
1 of 2
1

Your first problem is that math.isnan() does not accept string values as input. You can try and see math.isnan('any string').

Because you are in the pandas dataframe already, you are better off to use Pandas to handle your case. For example:

df.dropna()           # column-wise nan drop
df.dropna(axis=1)     # row-wise nan drop

Note that there are very useful arguments for additional convenience in dropna(), so do check those out from the doctring or corresponding manual entries.

As a word of advice for along the journey, when you work with pandas, it's good to keep in mind that often whatever you want to do, is easier to do just within native pandas functionality. Because Pandas is kind of a gold standard for this type of work, generally speaking whatever you are thinking you want to do (if it makes sense) the Pandas community had already thought of (and implemented) it.

2 of 2
1

Your given dataframe is tough to replicate. Here is a sample df:

df = pd.DataFrame([["11","1", np.nan], [np.nan,"1", "2"], ['abc','def','ijk']],
             columns=["ix","a", "b"])
>>df

    a   b   c
0   11  1   NaN
1   NaN 1   2
2   abc def ijk

from the docs : df.dropna()

df.dropna()

This returns all the rows which doesnot have any nan in any columns. Output:

    a   b   c
2   abc def ijk

for filtering columns which doesnot have any nan:

df.dropna(axis=1)

    b
0   1
1   1
2   def

For finding rows with nan:

df_nan= df.drop(list(df.dropna().index))

Also please check the how= builtin function which allows you to drop na values for any or all rows/columns depending on the axis selected.

🌐
Turing
turing.com › kb › nan-values-in-python
How to Check for NaN Values in Python?[With Examples]
The isna() function returns a Boolean Series where True represents NaN values and False represents non-NaN values. In Python, you can also use the comparison operator != to check for NaN values.
🌐
Note.nkmk.me
note.nkmk.me › home › python
What is nan in Python (float('nan'), math.nan, np.nan) | note.nkmk.me
May 9, 2023 - In Python, the float type has nan. nan stands for "not a number" and is defined by the IEEE 754 floating-point standard. NaN - Wikipedia nan is a float value in Python Create nan: float('nan'), math.n ...
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › python › check for nan values in python
Check for NaN Values in Python Using math.isnan | Sentry
October 2, 2026 - import math def is_nan(value): try: return math.isnan(value) except TypeError: return False nan = float('nan') zero = 0 one = 1 hello = "Hello!" print(is_nan(nan)) # will print True print(is_nan(zero)) # will print False print(is_nan(one)) # will print False print(is_nan(hello)) # will print False ... Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski. SEE EPISODES ... David Y. — September 23, 2026 ... David Y. — October 2, 2026 · Get the current script file's full directory path in Python
🌐
W3Schools
w3schools.com › python › ref_math_isnan.asp
Python math.isnan() Method
The math.isnan() method checks whether a value is NaN (Not a Number), or not.
Top answer
1 of 2
6

Methods for this already exist, particularly because of the weird properties of NaNs. One of them can be found in the math library, math.isnan and numpy already has a method implemented for this as well, numpy.isnan. They both deal with all three kinds of NaNs shown in your code (but the numpy version is vectorized):

import math
import numpy as np

list(map(math.isnan, [float("nan"), math.nan, np.nan]))
# [True, True, True]

np.isnan([float("nan"), math.nan, np.nan]) 
# array([ True,  True,  True])

If you are using pandas, pandas.isna is also interesting because it considers None and pandas.NaT (Not a Time) as missing values as well:

import pandas as pd

pd.isna([float("nan"), math.nan, np.nan, None, pd.NaT])
# array([ True,  True,  True,  True,  True])

Your code has a potential flaw, it does not return True only for NaNs (although it does return True for all NaNs), but for all objects which are not equal to themselves. In particular, it will think any instance of this class is NaN (probably true, but not necessarily):

class A:
    def __equal__(self, other):
        return False
2 of 2
2

IMHO your function is correct and readable as it is. If I see something like x != x in any language my mind jumps immediately to NaN, regardless of the type. So if you have something like a missing string or date or whatever, this test still makes sense.

Regarding the report from sonarsource. It is always helpful to read the rationale behind a rule. If you look here there are nice examples why this rule generally makes sense. I don't think this applies in your case and you can ignore it.

Some nitpicks:

  1. I would directly return without creating a temporary. The same is true for printing.
  2. There are two spaces after is_nan =
  3. Your functions are not in a class and are really functions. Even if they were methods it would be very redundant to add it. Why don't you just call it is_nan?
import math
import numpy as np

v1 = float('nan')
v2 = math.nan
v3 = np.nan

def is_nan(value) -> bool:
    return value != value

print(is_nan(v1))
print(is_nan(v2))
print(is_nan(v3))
🌐
Finxter
blog.finxter.com › home › learn python blog › converting python string to float dealing with nan values
Converting Python String to Float Dealing with NaN Values - Be on the Right Side of Change
February 19, 2024 - Conversion of a string that explicitly contains ‘NaN’ to a float can be straightforwardly achieved by the built-in float() function, and the math.isnan() function can be used to check for the resultant NaN value.
🌐
Digis
digiscorp.com › python-check-if-value-is-nan-a-complete-overview
Python Check If Value Is NaN: A Complete Overview
September 7, 2026 - Learn how to check if a value is NaN Python using methods like numpy.isnan, math.isnan, and pandas.isna. Discover the best practices for identifying and handling NaN values efficiently in your Python projects.
🌐
Python.org
discuss.python.org › python help › how to replace `nan` without external libraries when strings are present?
How to replace `nan` without external libraries when strings are present? - Python Help - Discussions on Python.org
July 2, 2024 - Given a dictionary whose keys are strings and values are a combination of strings, floats, integers and math.nan import math d = {"name": "Ryan", "value": 123.456, "other_value": math.nan} I am trying to convert the nan values to an empty string like this: {'name': 'Ryan', 'value': 123.456, 'other_value': ''} The following gives an error: {k: "" if math.isnan(v) else v for k, v in d.items()} TypeError: must be real number, not str What is the best way to check for nan that doesn’t break o...
🌐
GeeksforGeeks
geeksforgeeks.org › python › check-for-nan-values-in-python
Check For NaN Values in Python - GeeksforGeeks
July 23, 2025 - Pandas provides the isnull() function, which is useful for checking NaN values in DataFrames and Series.
🌐
GeeksforGeeks
geeksforgeeks.org › python › check-if-the-value-is-infinity-or-nan-in-python
Check if the value is infinity or NaN in Python - GeeksforGeeks
July 23, 2025 - In this article, we will check whether the given value is NaN or Infinity. This can be done using the math module.