Skip to content
Advertisement

Control how NAs are displayed with pandas styler

I am trying to use the na_rep argument of df.style.format() to control how cells with NaN are shown in the table.

Documentation: https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html

Reproducible code:

import numpy as np; import pandas as pd

df = pd.DataFrame({"col1":[1,2,3],"col2":[1,np.nan,2]})
df.style.format(na_rep='.')

I get this error message.

TypeError: format() got an unexpected keyword argument ‘na_rep’

Do you know a work around? Tks!

Advertisement

Answer

I ended up using a grey color for the text and the background of NA cells to hide the NAs

import numpy as np; import pandas as pd

df = pd.DataFrame({"col1":[1,2,3],"col2":[1,np.nan,2]})
s = df.style
s.applymap(lambda x: 'color: #E5E5E5' if pd.isnull(x) else '')
s.applymap(lambda x: 'background: #E5E5E5' if pd.isnull(x) else '')

This is what it looks like:

enter image description here

Advertisement