Applying styling to Pandas dataframe saved to HTML file

前端 未结 1 1862
半阙折子戏
半阙折子戏 2021-02-04 20:16

I have a Pandas dataframe inside of a Jupyter / IPython notebook. The dataframe\'s style as an HTML table inside of Jupyter is pretty nice. The header row has bold style, the fo

1条回答
  •  無奈伤痛
    2021-02-04 20:44

    I wrote a Python function that basically adds an HTML ''' result += '

    %s

    \n' % title if type(df) == pd.io.formats.style.Styler: result += df.render() else: result += df.to_html(classes='wide', escape=False) result += ''' ''' with open(filename, 'w') as f: f.write(result)

    Here's the resulting HTML when you write it to an .html file. Note how the dataframe's to_html() output fits into the middle.

    Below is some example usage of my function. I first load up a dataset from sklearn to demonstrate.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    
    iris = load_iris()
    data1 = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
                         columns=iris['feature_names'] + ['target'])
    data1.head()
    

    In Jupyter / IPython Notebook, the table looks pretty nice:

    I can write out the dataframe to an HTML file with the usual to_html() function like this:

    data1.to_html('iris.html')
    

    However, the result doesn't look good, as shown below. The border is thick and font is not pleasant because this is just a

    ...
    with no styling.

    To make the dataframe look better in HTML, I used my function above.

    write_to_html_file(data1, 'Iris data set', 'iris2.html')
    

    The table looks much nicer now because I applied styling. I also added row highlighting.

    0 讨论(0)
提交回复
热议问题