Say with this DataFrame
df = pd.DataFrame({'name' : ['A','B'], 'date' : pd.to_datetime(['2000-01-01','2000-01-02']), 'value' : [np.nan, 1]}) date name value 0 2000-01-01 A NaN 1 2000-01-02 B 1.0
How can I check which element is nan
inside df.applymap
? (ie, not using df.isnull
)
The problem comes from where I want to use the pandas html styling. We have the built-in nan highlighting
df.style.highlight_null()
but it changes the background colour, instead I want “nan” to be displayed in red.
So I need to do it myself with applymap
df.style.applymap(lambda x: 'color: red' if isnan(x) else '')
But how can I check if a value is nan, when it can also be datetime/string? np.isnan
will fail on strings. np.isreal(x) and np.isnan(x)
also fails on datetime.
Advertisement
Answer
You can use pd.isnull(), which deals with a wider range of types for missing values check:
import pandas as pd df.style.applymap(lambda x: 'color: red' if pd.isnull(x) else '')