如何向 Pandas 样式器对象添加边框?

Jea*_*123 0 python dataframe pandas-styles

我有一个数据框 df,如下所示:

姓名
鲍勃 周一
约翰 周四
山姆 星期五
鲍勃 周一
凯蒂 星期日
凯尔 周二
凯蒂 周六
鲍勃 周三
凯蒂 星期日
山姆 周四
星期五

考虑到名称在名称列中出现的频率,以下代码会突出显示整行:

cmap = {1: 'green', 2: 'yellow', 3: 'red'}
freq = df['Name'].map(df['Name'].value_counts())
colors = freq.map(cmap).radd('background-color: ')

df.style.apply(lambda s: colors)
Run Code Online (Sandbox Code Playgroud)

但是,当我使用 .render() 将样式器对象转换为 html 以在电子邮件中发送时,表中没有边框。将数据框转换为样式器对象然后转换为 HTML 表时如何保留边框?

Jea*_*123 5

当我找到答案时,我几乎把问题打印出来了,所以我想我会把它作为问答来进行。

创建样式器对象时,一个接一个地串接样式效果很好。例如:

df.style.apply(lambda s: colors).set_table_styles(
    [{"selector": "", "props": [("border", "1px solid")]},
      {"selector": "tbody td", "props": [("border", "1px solid")]},
     {"selector": "th", "props": [("border", "1px solid")]}])
Run Code Online (Sandbox Code Playgroud)

然后在 set_table_styles 中可以更改不同的参数来格式化边框。