首页 > 解决方案 > 如何设置 Pandas Datafrane 标题的字体?

问题描述

我试图在 Jupyter 笔记本中并排显示两个表格。我有一些代码可以做到这一点:

header = ["Metric", "Test dataset"]

table1 = [["accuracy",               accuracy_test],
          ["precision",              precision_test],
          ["recall",                 recall_test],
          ["misclassification rate", misclassification_rate_test],
          ["F1",                     F1_test],
          ["r2",                     r2_test],
          ["AUC",                    auc_test],
          ["mse",                    mse_test],
          ["logloss",                logloss_test]
          ]

table2 = [['accuracy',               0.91943799],
          ['precision',              0.89705603],
          ['recall',                 0.94877461],
          ['misclassification rate', 0.08056201],
          ['F1',                     0.92219076],
          ['r2',                     0.67773888],
          ['AUC',                    0.91924997],
          ['mse',                    0.08056201],
          ['logloss',                2.78255718]]

def display_side_by_side(dfs:list, captions:list):
    output = ""
    combined = dict(zip(captions, dfs))
    styles = [
        dict(selector="caption", props=[("caption-side", "center"), ("font-size", "100%"), ("color", )])]
    for caption, df in combined.items():
        output += df.style.set_table_attributes("style='display:inline; font-size:110%' ").set_caption(caption)._repr_html_()
        output += "\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0"
    display(HTML(output))

df1 = pd.DataFrame(table1, columns=header)
df2 = pd.DataFrame(table2, columns=header)

display_side_by_side([df1, df2], ['Current Performance', 'Previous Performance'])

我的 Jupyter 笔记本中的输出如下所示:

在此处输入图像描述

请注意,标题为浅色,并且不在表格上方居中。我怎样才能解决这个问题?

查尔斯

标签: htmljupyter-notebooksklearn-pandas

解决方案


您已经定义了样式,但没有包含它们。语法也有点不正确。

styles = [dict(selector="caption", 
    props=[("text-align", "center"),
    ("font-size", "120%"),
    ("color", 'black')])]    # the color value can not be None
# ...

    output += df.style.set_table_attributes("style='display:inline; font-size:110%' ")
        .set_caption(caption)
        .set_table_styles(styles)    # include styles
        ._repr_html_()

推荐阅读