如何仅更改第一个“列名”熊猫的字体

时间:2019-09-15 22:22:36

标签: python pandas

我有3列的Panda Dataframe。我只需要为第一个“列名称”更改字体,并使第二列和第三列名称具有不同的字体。我正在使用渲染功能生成CSS标签。

我尝试使用df.style.set_table_styles函数,但是它对所有列名(列标题)都应用了相同的字体。

有没有一种方法可以将样式函数的应用限制为仅第一列标题?

df.style.set_table_styles
df.style.set_properties(subset=df.columns[0], **{'text-align':'left','font-family': 'Courier','font-size': '10px'})

df = pd.DataFrame({'A':[1,2,3],
               'B':[4,5,6],
               'C':[7,8,9],
               'D':[1,3,5],
               'E':[5,3,6],
               'F':[7,4,3]})
df=df.style.set_properties(subset=df.columns[0], **{'text-align':'left','font-family': 'Cambria','font-size': '10px'})
print(df.render())

我只希望'A'具有Cambria字体,其余(B,C,D等)具有不同的字体。

1 个答案:

答案 0 :(得分:1)

您必须使用一些 CSS 技巧来选择第一列标题:

def set_header_font():
    return [dict(selector="th:nth-child(2)",
                 props=[("font-size", "14pt"),("font-family", 'Cambria')])]

df.style.set_table_styles(set_header_font())

nth-child(2) 选择表中的第二个 th 元素 --- second th 因为第一个 th 用于您的 DataFrame 索引名称(这是一个空的字符串在你的情况))。