如何在 Pandas 数据框中的单个列中以不同方式突出显示每个唯一字符串值?
How to highlight each unique string value differently in a single column in Pandas dataframe?
我在 Pandas 中有一个数据框,我想让它对用户更具可读性。有很多 columns/rows 以及字符串和浮点数的混合。
我有一列,我们称它为 'Type',它有大约 5 个唯一的可能值,比方说 'Fruit'、'Vegetable'、'Legume'、'Liquid', 'Meat'.
我希望 'Fruit' 始终突出显示,比方说 'yellow'。 'Vegetable' 应始终具有 'green' 的背景颜色,等等
如何在 Pandas 中生成此样式?
我 运行 遇到了很多问题,因为这不是典型的用例(大多数样式假设 integers/floats 被突出显示)。
我试过使用 applymap 但似乎无法弄清楚如何让它突出显示一个字符串并且只在一个列中。
谢谢!
def styler(col):
# We only want to apply style to the Type column
if col.name != 'Type':
return [''] * len(col)
bg_color = col.map({
'Fruit': 'yellow',
'Vegetable': 'green',
'Liquid': 'rgb(0,0,255)',
}).fillna('') # a fallback for fruits we haven't colorized
return 'background-color:' + bg_color
df.style.apply(styler)
颜色值使用CSS Colors specs
我在 Pandas 中有一个数据框,我想让它对用户更具可读性。有很多 columns/rows 以及字符串和浮点数的混合。
我有一列,我们称它为 'Type',它有大约 5 个唯一的可能值,比方说 'Fruit'、'Vegetable'、'Legume'、'Liquid', 'Meat'.
我希望 'Fruit' 始终突出显示,比方说 'yellow'。 'Vegetable' 应始终具有 'green' 的背景颜色,等等
如何在 Pandas 中生成此样式?
我 运行 遇到了很多问题,因为这不是典型的用例(大多数样式假设 integers/floats 被突出显示)。
我试过使用 applymap 但似乎无法弄清楚如何让它突出显示一个字符串并且只在一个列中。
谢谢!
def styler(col):
# We only want to apply style to the Type column
if col.name != 'Type':
return [''] * len(col)
bg_color = col.map({
'Fruit': 'yellow',
'Vegetable': 'green',
'Liquid': 'rgb(0,0,255)',
}).fillna('') # a fallback for fruits we haven't colorized
return 'background-color:' + bg_color
df.style.apply(styler)
颜色值使用CSS Colors specs