如何在熊猫样式中突出显示类别dtype?

时间:2020-06-24 17:32:29

标签: python pandas

我能够突出显示'object'dtype,但是当我对'category'尝试相同的操作时,它失败了。

如何以熊猫样式同时突出显示“ object”和“ category” dtype?

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)

输出

但是我要同时突出显示对象和类别。

enter image description here

1 个答案:

答案 0 :(得分:3)

一种快速的解决方法是比较字符串表示形式:

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

输出:

enter image description here