使用与 Jupyter Notebook 相同的样式将 pandas 数据框渲染为 HTML

Rendering a pandas dataframe as HTML with same styling as Jupyter Notebook

我想以与 Jupyter Notebook 相同的方式将 pandas 数据帧渲染到 HTML,即所有花里胡哨的东西,比如漂亮的样式、列突出显示和单击时列排序。

pandas.to_html 只输出一个普通的 HTML table 并且需要手动设置样式等

jupyter 使用的 dataframe 渲染代码是否可以作为可在任何网络应用程序中使用的独立模块使用?

此外,js/css 文件等资产是否已与 jupyter 解耦,以便于重用?

首先要澄清的几点:

  • Pandas与样式没有任何关系,样式恰好在所有HTMLtable中,不只有数据框。通过在 Jupyter 中显示 HTML table(答案末尾的示例代码)可以轻松检查这一点。
  • 您的 Jupyter 或您安装的扩展程序之一似乎正在执行 "extra" 样式设置,默认样式不包括列排序或列突出显示。只有 odd/even 行着色和行突出显示(在 Jupyter 源代码和我本地的 Jupyter 安装中检查过)。这意味着我的答案可能不会包含您想要的所有样式。

答案

Is the dataframe rendering code used by jupyter available as a standalone module that can be used in any web app?

不完全是一个独立的模块,但是 table 的所有格式和样式似乎都附加到 rendered_html class。通过在 Firefox 中检查笔记本 HTML 仔细检查。
您可以直接使用上面链接的 .less 文件或将所需样式复制到您的 HTML。

Also, are the assets such as js/css files decoupled from jupyter so that they can be easily reused?

与任何精心设计的 Web 项目(以及实际上任何软件项目)一样,包和模块很好地分离。这意味着您可以毫不费力地重复使用项目中的大量代码。您可以在 Jupyter 源代码 here.

中找到大部分 .less 样式文件

检查样式是否适用于所有 HTML table 的示例:

from IPython.display import HTML

HTML('''<table>
  <thead><tr><th></th><th>a</th><th>b</th></tr></thead>
  <tbody>
    <tr><th>0</th><td>1</td><td>3</td></tr>
    <tr><th>1</th><td>2</td><td>4</td></tr>
  </tbody>
</table>''')

这很适合我

def getTableHTML(df):
    
    """
    From 
    
    Get a Jupyter like html of pandas dataframe
    
    """

    styles = [
        #table properties
        dict(selector=" ", 
             props=[("margin","0"),
                    ("font-family",'"Helvetica", "Arial", sans-serif'),
                    ("border-collapse", "collapse"),
                    ("border","none"),
    #                 ("border", "2px solid #ccf")
                       ]),

        #header color - optional
    #     dict(selector="thead", 
    #          props=[("background-color","#cc8484")
    #                ]),

        #background shading
        dict(selector="tbody tr:nth-child(even)",
             props=[("background-color", "#fff")]),
        dict(selector="tbody tr:nth-child(odd)",
             props=[("background-color", "#eee")]),

        #cell spacing
        dict(selector="td", 
             props=[("padding", ".5em")]),

        #header cell properties
        dict(selector="th", 
             props=[("font-size", "100%"),
                    ("text-align", "center")]),


    ]
    return (df.style.set_table_styles(styles)).render()
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
getTableHTML(iris)