BhishanPoudel
BhishanPoudel

Reputation: 17164

How to style highlight categorical dtype in pandas style?

I was able to highlight 'object' dtype, but when I tried the same thing for 'category', it fails.

How to highlight both 'object' and 'category' dtype in pandas style?

MWE

# code
import numpy as np
import pandas as pd
import seaborn as sns
df = sns.load_dataset('titanic')
df1 = df.dtypes.to_frame()

# this only highlights 'object'
df1.style.apply(lambda x: ["background: salmon"
                        if  v =='object' else "" for v in x], axis = 1)

# this fails
df1.style.apply(lambda x: ["background: salmon"
                        if  v in ['object','category'] else "" for v in x], axis = 1)

output

But I want both object and category be highlighted.

enter image description here

Upvotes: 1

Views: 174

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

A quick fix is to compare the string representation:

# this fails
df1.style.apply(lambda x: ["background: salmon"
                        if  str(v) in ['object','category'] else "" for v in x], axis = 1)

Output:

enter image description here

Upvotes: 3

Related Questions