1

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.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
jf328
  • 6,841
  • 10
  • 58
  • 82

2 Answers2

8

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 '')

enter image description here

Psidom
  • 209,562
  • 33
  • 339
  • 356
0

You can also use the fact that floating point ̀NaN` values are not equal to themselves:

df.style.applymap(lambda x: '' if x==x else 'color: red')
Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110