Replicating Jupyter Notebook Pandas dataframe HTML printout

前端 未结 2 638
野性不改
野性不改 2021-01-05 10:13

I\'m trying to replicate the output that jupyter uses for a pandas dataframe in their notebooks to html/css/js so that it\'s returnable by Flask jsonify as html

2条回答
  •  臣服心动
    2021-01-05 10:34

    I've made a few changes to your code to get the functionality you want:

    • Pandas dataframes are styled with two special HTML tags for tables, namely thead for the header and tbody for the body. We can use this to specify the highlighting behavior as body-only
    • CSS has "even" and "odd" properties which you can use to add shading effects to tables.
    • In order for hover to work with the background shading specified, it must be called last not first

    In Jupyter Notebook:

    import pandas as pd
    import numpy as np
    from IPython.display import HTML
    
    def hover(hover_color="#add8e6"):
        return dict(selector="tbody tr:hover",
                props=[("background-color", "%s" % hover_color)])
    
    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", "125%"),
                    ("text-align", "center")]),
    
        #caption placement
        dict(selector="caption", 
             props=[("caption-side", "bottom")]),
    
        #render hover last to override background-color
        hover()
    ]
    html = (df.style.set_table_styles(styles)
          .set_caption("Hover to highlight."))
    html
    

    ...but is it still beautiful when we output the HTML file?? Yes. You can do some more CSS styling to get it just right (font-size, font-family, text-decoration, margin/padding, etc) but this gives you a start. See below:

    print(html.render())
    

      
    
    Hover to highlight.
    0
    first second
    bar one -0.130634
    two 1.17685
    baz one 0.500367
    two 0.555932
    foo one -0.744553
    two -1.41269
    qux one 0.726728
    two -0.683555

提交回复
热议问题