How to Get Rows or Columns with NaN (null) Values in a Pandas DataFrame
Let’s see how to get rows or columns with one or more NaN values in a Pandas DataFrame.
1. Get rows with NaN
We can use isna()
or isnull()
to get all rows with NaN
values.
df[df.isna().any(axis=1)]
df[df.isnull().any(axis=1)]
isnull()
is an alias ofisna()
. Many preferisna()
for semantic consistency (e.g.np.isnan()
,dropna()
, andfillna()
all handle missing values).
2. Get columns with NaN
Let’s retrieve all rows of all columns that contain a NaN
value.
df.loc[:, df.isna().any()]
3. Get each row’s NaN
status
Given a single column, pd.isnull()
will tell us the NaN
status of each row (i.e. whether or not it contains any NaN
values in that column).
pd.isnull(df['col'])
4. Get NaN
count per column
We can also get the count of NaN
values per column using isnull()
and sum()
.
df.isnull().sum()