Say with this DataFrame
JavaScript
x
6
1
df = pd.DataFrame({'name' : ['A','B'], 'date' : pd.to_datetime(['2000-01-01','2000-01-02']), 'value' : [np.nan, 1]})
2
3
date name value
4
0 2000-01-01 A NaN
5
1 2000-01-02 B 1.0
6
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
JavaScript
1
2
1
df.style.highlight_null()
2
but it changes the background colour, instead I want “nan” to be displayed in red.
So I need to do it myself with applymap
JavaScript
1
2
1
df.style.applymap(lambda x: 'color: red' if isnan(x) else '')
2
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:
JavaScript
1
3
1
import pandas as pd
2
df.style.applymap(lambda x: 'color: red' if pd.isnull(x) else '')
3