代码之家  ›  专栏  ›  技术社区  ›  ccpizza

以与Jupyter笔记本相同的样式将数据帧呈现为HTML

  •  7
  • ccpizza  · 技术社区  · 6 年前

    我想呈现一个熊猫数据框到HTML的方式与Jupyter笔记本一样,也就是说,所有的铃铛和wistles像好看的样式,列突出显示,列排序点击。

    enter image description here

    pandas.to_html

    jupyter使用的数据帧呈现代码是否可以作为一个独立的模块在任何web应用程序中使用?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Qusai Alothman    6 年前

    首先要澄清的几点:

    • 全部的
    • 似乎您的Jupyter或您安装的扩展正在进行“额外”样式设置,默认样式不包括列排序或列高亮显示。只有奇数/偶数行着色和行高亮显示(在Jupyter源代码和本地Jupyter安装中进行了检查)。这意味着我的答案可能不包括你想要的所有样式。

    答案

    jupyter使用的数据帧呈现代码是否可以作为一个独立的模块在任何web应用程序中使用?

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

    另外,js/css文件等资产是否与jupyter解耦,以便可以轻松重用?

    与任何设计良好的web项目(实际上是任何软件项目)一样,包和模块是完全分开的。这意味着您可以以最小的工作量重用项目中的大量代码。你可以找到大部分的 .更少 Jupyter源代码中的样式文件 here


    检查样式是否发生在所有HTML表上的示例:

    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>''')
    
        2
  •  2
  •   DougR    4 年前

    def getTableHTML(df):
        
        """
        From https://stackoverflow.com/a/49687866/2007153
        
        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)