Pandas: print column name with missing values
Oneliner -
[col for col in df.columns if df[col].isnull().any()]
df.isnull().any()
generates a boolean array (True if the column has a missing value, False otherwise). You can use it to index into df.columns
:
df.columns[df.isnull().any()]
will return a list of the columns which have missing values.
df = pd.DataFrame({'A': [1, 2, 3],
'B': [1, 2, np.nan],
'C': [4, 5, 6],
'D': [np.nan, np.nan, np.nan]})
df
Out:
A B C D
0 1 1.0 4 NaN
1 2 2.0 5 NaN
2 3 NaN 6 NaN
df.columns[df.isnull().any()]
Out: Index(['B', 'D'], dtype='object')
df.columns[df.isnull().any()].tolist() # to get a list instead of an Index object
Out: ['B', 'D']