Apply CSS class to Pandas DataFrame using to_html





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







20















I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.



"classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table"
from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html



I am able to render a styled DataFrame like this (for example):



df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
f.write(myhtml)


How can I style html output from a DataFrame using "classes" with "to_html" like this:



df.to_html('myhtml.html',classes=<something here>)









share|improve this question




















  • 1





    How do you want the html file to look like?

    – U9-Forward
    Jun 12 '18 at 0:40











  • I would like to apply the same properties that were given in the "set_properties" method in the example.

    – sparrow
    Jun 12 '18 at 0:42






  • 1





    Create a string "<style type='text/css'>" + myStyles + "</style>" and append it to the string given by df.to_html().

    – eric99
    Jun 20 '18 at 4:31








  • 1





    When using with to open file, you don't need to close() it manually. When existing with scope, the variable will be destroyed by the garbage collector, and the file will be closed automatically.

    – igrinis
    Jun 24 '18 at 11:28













  • thanks @igrinis. I've edited my question.

    – sparrow
    Jun 25 '18 at 21:45


















20















I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.



"classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table"
from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html



I am able to render a styled DataFrame like this (for example):



df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
f.write(myhtml)


How can I style html output from a DataFrame using "classes" with "to_html" like this:



df.to_html('myhtml.html',classes=<something here>)









share|improve this question




















  • 1





    How do you want the html file to look like?

    – U9-Forward
    Jun 12 '18 at 0:40











  • I would like to apply the same properties that were given in the "set_properties" method in the example.

    – sparrow
    Jun 12 '18 at 0:42






  • 1





    Create a string "<style type='text/css'>" + myStyles + "</style>" and append it to the string given by df.to_html().

    – eric99
    Jun 20 '18 at 4:31








  • 1





    When using with to open file, you don't need to close() it manually. When existing with scope, the variable will be destroyed by the garbage collector, and the file will be closed automatically.

    – igrinis
    Jun 24 '18 at 11:28













  • thanks @igrinis. I've edited my question.

    – sparrow
    Jun 25 '18 at 21:45














20












20








20


10






I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.



"classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table"
from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html



I am able to render a styled DataFrame like this (for example):



df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
f.write(myhtml)


How can I style html output from a DataFrame using "classes" with "to_html" like this:



df.to_html('myhtml.html',classes=<something here>)









share|improve this question
















I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.



"classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table"
from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html



I am able to render a styled DataFrame like this (for example):



df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
f.write(myhtml)


How can I style html output from a DataFrame using "classes" with "to_html" like this:



df.to_html('myhtml.html',classes=<something here>)






python pandas dataframe






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 25 '18 at 21:45







sparrow

















asked Jun 12 '18 at 0:30









sparrowsparrow

3,24432340




3,24432340








  • 1





    How do you want the html file to look like?

    – U9-Forward
    Jun 12 '18 at 0:40











  • I would like to apply the same properties that were given in the "set_properties" method in the example.

    – sparrow
    Jun 12 '18 at 0:42






  • 1





    Create a string "<style type='text/css'>" + myStyles + "</style>" and append it to the string given by df.to_html().

    – eric99
    Jun 20 '18 at 4:31








  • 1





    When using with to open file, you don't need to close() it manually. When existing with scope, the variable will be destroyed by the garbage collector, and the file will be closed automatically.

    – igrinis
    Jun 24 '18 at 11:28













  • thanks @igrinis. I've edited my question.

    – sparrow
    Jun 25 '18 at 21:45














  • 1





    How do you want the html file to look like?

    – U9-Forward
    Jun 12 '18 at 0:40











  • I would like to apply the same properties that were given in the "set_properties" method in the example.

    – sparrow
    Jun 12 '18 at 0:42






  • 1





    Create a string "<style type='text/css'>" + myStyles + "</style>" and append it to the string given by df.to_html().

    – eric99
    Jun 20 '18 at 4:31








  • 1





    When using with to open file, you don't need to close() it manually. When existing with scope, the variable will be destroyed by the garbage collector, and the file will be closed automatically.

    – igrinis
    Jun 24 '18 at 11:28













  • thanks @igrinis. I've edited my question.

    – sparrow
    Jun 25 '18 at 21:45








1




1





How do you want the html file to look like?

– U9-Forward
Jun 12 '18 at 0:40





How do you want the html file to look like?

– U9-Forward
Jun 12 '18 at 0:40













I would like to apply the same properties that were given in the "set_properties" method in the example.

– sparrow
Jun 12 '18 at 0:42





I would like to apply the same properties that were given in the "set_properties" method in the example.

– sparrow
Jun 12 '18 at 0:42




1




1





Create a string "<style type='text/css'>" + myStyles + "</style>" and append it to the string given by df.to_html().

– eric99
Jun 20 '18 at 4:31







Create a string "<style type='text/css'>" + myStyles + "</style>" and append it to the string given by df.to_html().

– eric99
Jun 20 '18 at 4:31






1




1





When using with to open file, you don't need to close() it manually. When existing with scope, the variable will be destroyed by the garbage collector, and the file will be closed automatically.

– igrinis
Jun 24 '18 at 11:28







When using with to open file, you don't need to close() it manually. When existing with scope, the variable will be destroyed by the garbage collector, and the file will be closed automatically.

– igrinis
Jun 24 '18 at 11:28















thanks @igrinis. I've edited my question.

– sparrow
Jun 25 '18 at 21:45





thanks @igrinis. I've edited my question.

– sparrow
Jun 25 '18 at 21:45












2 Answers
2






active

oldest

votes


















21





+50









Pandas' to_html simply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the <table> a class attribute that will be referenced in a previously created CSS document that styles it. Therefore, incorporate to_html into a wider HTML document build that references an external CSS.



Interestingly, to_html adds dual classes <table class="dataframe mystyle"> which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data.



Data



import pandas as pd
import numpy as np

pd.set_option('display.width', 1000)
pd.set_option('colheader_justify', 'center')

np.random.seed(6182018)
demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50),
'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50),
'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50),
'num1': np.random.randn(50)*100,
'num2': np.random.uniform(0,1,50),
'num3': np.random.randint(100, size=50),
'bool': np.random.choice([True, False], 50)
},
columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
)


print(demo_df.head(10))
# date analysis_tool num1 database num2 os num3 bool
# 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True
# 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False
# 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False
# 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False
# 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True
# 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True
# 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True
# 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False
# 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False
# 9 2018-04-12 r 38.963967 postgres 0.266604 windows 7 46 False


CSS (save as df_style.css)



/* includes alternating gray and white with on-hover color */

.mystyle {
font-size: 11pt;
font-family: Arial;
border-collapse: collapse;
border: 1px solid silver;

}

.mystyle td, th {
padding: 5px;
}

.mystyle tr:nth-child(even) {
background: #E0E0E0;
}

.mystyle tr:hover {
background: silver;
cursor: pointer;
}


Pandas



pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>

html_string = '''
<html>
<head><title>HTML Pandas Dataframe with CSS</title></head>
<link rel="stylesheet" type="text/css" href="df_style.css"/>
<body>
{table}
</body>
</html>.
'''

# OUTPUT AN HTML FILE
with open('myhtml.html', 'w') as f:
f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))




OUTPUT



HTML (references df_style.css, assumed in same directory; see class argument in table)



<html>
<head><title>HTML Pandas Dataframe with CSS</title></head>
<link rel="stylesheet" type="text/css" href="df_style.css"/>
<body>
<table border="1" class="dataframe mystyle">
<thead>
<tr style="text-align: center;">
<th></th>
<th>date</th>
<th>analysis_tool</th>
<th>num1</th>
<th>database</th>
<th>num2</th>
<th>os</th>
<th>num3</th>
<th>bool</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>2018-04-21</td>
<td>pandas</td>
<td>153.474246</td>
<td>mysql</td>
<td>0.658533</td>
<td>ios</td>
<td>74</td>
<td>True</td>
</tr>
<tr>
<th>1</th>
<td>2018-04-13</td>
<td>sas</td>
<td>199.461669</td>
<td>sqlite</td>
<td>0.656985</td>
<td>windows 7</td>
<td>11</td>
<td>False</td>
</tr>
<tr>
<th>2</th>
<td>2018-06-09</td>
<td>stata</td>
<td>12.918608</td>
<td>oracle</td>
<td>0.495707</td>
<td>android</td>
<td>25</td>
<td>False</td>
</tr>
<tr>
<th>3</th>
<td>2018-04-24</td>
<td>spss</td>
<td>88.562111</td>
<td>sql server</td>
<td>0.113580</td>
<td>windows 7</td>
<td>42</td>
<td>False</td>
</tr>
<tr>
<th>4</th>
<td>2018-05-05</td>
<td>spss</td>
<td>110.231277</td>
<td>oracle</td>
<td>0.660977</td>
<td>windows 10</td>
<td>76</td>
<td>True</td>
</tr>
...
</tbody>
</table>
</body>
</html>


HTML Output






share|improve this answer
























  • Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

    – sparrow
    Jun 20 '18 at 16:19






  • 2





    I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

    – Parfait
    Jun 20 '18 at 17:11











  • df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

    – sparrow
    Jun 20 '18 at 19:31






  • 1





    Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

    – Parfait
    Jun 20 '18 at 19:38











  • Thanks, I still have a bit to learn ;).

    – sparrow
    Jun 20 '18 at 19:39



















0














Here's how I did it



Create a text file for css code and write down your css code here, say css_style.txt
Now read this txt file as a string in your python file



with open('css_style.txt', 'r') as myfile:
style = myfile.read()



Now in HTML code



"""<html><head>Something Something</head>{1}<div>{0}</div></html>""".format(some_panda_dataframe.to_html,style)


Here in my case css_style.txt file is



<style>
table {
border-collapse: collapse;
width: 100%;
}

th {
text-align: center;
padding: 8px;
}

td {
text-align: left;
padding: 8px;
}

tr:nth-child(even){background-color: #FFD5D5}

th {
background-color: #0000FF;
color: white;
}
</style>





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50807744%2fapply-css-class-to-pandas-dataframe-using-to-html%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    21





    +50









    Pandas' to_html simply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the <table> a class attribute that will be referenced in a previously created CSS document that styles it. Therefore, incorporate to_html into a wider HTML document build that references an external CSS.



    Interestingly, to_html adds dual classes <table class="dataframe mystyle"> which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data.



    Data



    import pandas as pd
    import numpy as np

    pd.set_option('display.width', 1000)
    pd.set_option('colheader_justify', 'center')

    np.random.seed(6182018)
    demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
    'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50),
    'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50),
    'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50),
    'num1': np.random.randn(50)*100,
    'num2': np.random.uniform(0,1,50),
    'num3': np.random.randint(100, size=50),
    'bool': np.random.choice([True, False], 50)
    },
    columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
    )


    print(demo_df.head(10))
    # date analysis_tool num1 database num2 os num3 bool
    # 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True
    # 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False
    # 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False
    # 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False
    # 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True
    # 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True
    # 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True
    # 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False
    # 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False
    # 9 2018-04-12 r 38.963967 postgres 0.266604 windows 7 46 False


    CSS (save as df_style.css)



    /* includes alternating gray and white with on-hover color */

    .mystyle {
    font-size: 11pt;
    font-family: Arial;
    border-collapse: collapse;
    border: 1px solid silver;

    }

    .mystyle td, th {
    padding: 5px;
    }

    .mystyle tr:nth-child(even) {
    background: #E0E0E0;
    }

    .mystyle tr:hover {
    background: silver;
    cursor: pointer;
    }


    Pandas



    pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>

    html_string = '''
    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    {table}
    </body>
    </html>.
    '''

    # OUTPUT AN HTML FILE
    with open('myhtml.html', 'w') as f:
    f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))




    OUTPUT



    HTML (references df_style.css, assumed in same directory; see class argument in table)



    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    <table border="1" class="dataframe mystyle">
    <thead>
    <tr style="text-align: center;">
    <th></th>
    <th>date</th>
    <th>analysis_tool</th>
    <th>num1</th>
    <th>database</th>
    <th>num2</th>
    <th>os</th>
    <th>num3</th>
    <th>bool</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <th>0</th>
    <td>2018-04-21</td>
    <td>pandas</td>
    <td>153.474246</td>
    <td>mysql</td>
    <td>0.658533</td>
    <td>ios</td>
    <td>74</td>
    <td>True</td>
    </tr>
    <tr>
    <th>1</th>
    <td>2018-04-13</td>
    <td>sas</td>
    <td>199.461669</td>
    <td>sqlite</td>
    <td>0.656985</td>
    <td>windows 7</td>
    <td>11</td>
    <td>False</td>
    </tr>
    <tr>
    <th>2</th>
    <td>2018-06-09</td>
    <td>stata</td>
    <td>12.918608</td>
    <td>oracle</td>
    <td>0.495707</td>
    <td>android</td>
    <td>25</td>
    <td>False</td>
    </tr>
    <tr>
    <th>3</th>
    <td>2018-04-24</td>
    <td>spss</td>
    <td>88.562111</td>
    <td>sql server</td>
    <td>0.113580</td>
    <td>windows 7</td>
    <td>42</td>
    <td>False</td>
    </tr>
    <tr>
    <th>4</th>
    <td>2018-05-05</td>
    <td>spss</td>
    <td>110.231277</td>
    <td>oracle</td>
    <td>0.660977</td>
    <td>windows 10</td>
    <td>76</td>
    <td>True</td>
    </tr>
    ...
    </tbody>
    </table>
    </body>
    </html>


    HTML Output






    share|improve this answer
























    • Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

      – sparrow
      Jun 20 '18 at 16:19






    • 2





      I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

      – Parfait
      Jun 20 '18 at 17:11











    • df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

      – sparrow
      Jun 20 '18 at 19:31






    • 1





      Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

      – Parfait
      Jun 20 '18 at 19:38











    • Thanks, I still have a bit to learn ;).

      – sparrow
      Jun 20 '18 at 19:39
















    21





    +50









    Pandas' to_html simply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the <table> a class attribute that will be referenced in a previously created CSS document that styles it. Therefore, incorporate to_html into a wider HTML document build that references an external CSS.



    Interestingly, to_html adds dual classes <table class="dataframe mystyle"> which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data.



    Data



    import pandas as pd
    import numpy as np

    pd.set_option('display.width', 1000)
    pd.set_option('colheader_justify', 'center')

    np.random.seed(6182018)
    demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
    'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50),
    'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50),
    'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50),
    'num1': np.random.randn(50)*100,
    'num2': np.random.uniform(0,1,50),
    'num3': np.random.randint(100, size=50),
    'bool': np.random.choice([True, False], 50)
    },
    columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
    )


    print(demo_df.head(10))
    # date analysis_tool num1 database num2 os num3 bool
    # 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True
    # 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False
    # 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False
    # 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False
    # 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True
    # 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True
    # 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True
    # 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False
    # 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False
    # 9 2018-04-12 r 38.963967 postgres 0.266604 windows 7 46 False


    CSS (save as df_style.css)



    /* includes alternating gray and white with on-hover color */

    .mystyle {
    font-size: 11pt;
    font-family: Arial;
    border-collapse: collapse;
    border: 1px solid silver;

    }

    .mystyle td, th {
    padding: 5px;
    }

    .mystyle tr:nth-child(even) {
    background: #E0E0E0;
    }

    .mystyle tr:hover {
    background: silver;
    cursor: pointer;
    }


    Pandas



    pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>

    html_string = '''
    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    {table}
    </body>
    </html>.
    '''

    # OUTPUT AN HTML FILE
    with open('myhtml.html', 'w') as f:
    f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))




    OUTPUT



    HTML (references df_style.css, assumed in same directory; see class argument in table)



    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    <table border="1" class="dataframe mystyle">
    <thead>
    <tr style="text-align: center;">
    <th></th>
    <th>date</th>
    <th>analysis_tool</th>
    <th>num1</th>
    <th>database</th>
    <th>num2</th>
    <th>os</th>
    <th>num3</th>
    <th>bool</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <th>0</th>
    <td>2018-04-21</td>
    <td>pandas</td>
    <td>153.474246</td>
    <td>mysql</td>
    <td>0.658533</td>
    <td>ios</td>
    <td>74</td>
    <td>True</td>
    </tr>
    <tr>
    <th>1</th>
    <td>2018-04-13</td>
    <td>sas</td>
    <td>199.461669</td>
    <td>sqlite</td>
    <td>0.656985</td>
    <td>windows 7</td>
    <td>11</td>
    <td>False</td>
    </tr>
    <tr>
    <th>2</th>
    <td>2018-06-09</td>
    <td>stata</td>
    <td>12.918608</td>
    <td>oracle</td>
    <td>0.495707</td>
    <td>android</td>
    <td>25</td>
    <td>False</td>
    </tr>
    <tr>
    <th>3</th>
    <td>2018-04-24</td>
    <td>spss</td>
    <td>88.562111</td>
    <td>sql server</td>
    <td>0.113580</td>
    <td>windows 7</td>
    <td>42</td>
    <td>False</td>
    </tr>
    <tr>
    <th>4</th>
    <td>2018-05-05</td>
    <td>spss</td>
    <td>110.231277</td>
    <td>oracle</td>
    <td>0.660977</td>
    <td>windows 10</td>
    <td>76</td>
    <td>True</td>
    </tr>
    ...
    </tbody>
    </table>
    </body>
    </html>


    HTML Output






    share|improve this answer
























    • Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

      – sparrow
      Jun 20 '18 at 16:19






    • 2





      I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

      – Parfait
      Jun 20 '18 at 17:11











    • df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

      – sparrow
      Jun 20 '18 at 19:31






    • 1





      Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

      – Parfait
      Jun 20 '18 at 19:38











    • Thanks, I still have a bit to learn ;).

      – sparrow
      Jun 20 '18 at 19:39














    21





    +50







    21





    +50



    21




    +50





    Pandas' to_html simply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the <table> a class attribute that will be referenced in a previously created CSS document that styles it. Therefore, incorporate to_html into a wider HTML document build that references an external CSS.



    Interestingly, to_html adds dual classes <table class="dataframe mystyle"> which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data.



    Data



    import pandas as pd
    import numpy as np

    pd.set_option('display.width', 1000)
    pd.set_option('colheader_justify', 'center')

    np.random.seed(6182018)
    demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
    'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50),
    'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50),
    'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50),
    'num1': np.random.randn(50)*100,
    'num2': np.random.uniform(0,1,50),
    'num3': np.random.randint(100, size=50),
    'bool': np.random.choice([True, False], 50)
    },
    columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
    )


    print(demo_df.head(10))
    # date analysis_tool num1 database num2 os num3 bool
    # 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True
    # 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False
    # 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False
    # 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False
    # 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True
    # 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True
    # 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True
    # 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False
    # 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False
    # 9 2018-04-12 r 38.963967 postgres 0.266604 windows 7 46 False


    CSS (save as df_style.css)



    /* includes alternating gray and white with on-hover color */

    .mystyle {
    font-size: 11pt;
    font-family: Arial;
    border-collapse: collapse;
    border: 1px solid silver;

    }

    .mystyle td, th {
    padding: 5px;
    }

    .mystyle tr:nth-child(even) {
    background: #E0E0E0;
    }

    .mystyle tr:hover {
    background: silver;
    cursor: pointer;
    }


    Pandas



    pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>

    html_string = '''
    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    {table}
    </body>
    </html>.
    '''

    # OUTPUT AN HTML FILE
    with open('myhtml.html', 'w') as f:
    f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))




    OUTPUT



    HTML (references df_style.css, assumed in same directory; see class argument in table)



    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    <table border="1" class="dataframe mystyle">
    <thead>
    <tr style="text-align: center;">
    <th></th>
    <th>date</th>
    <th>analysis_tool</th>
    <th>num1</th>
    <th>database</th>
    <th>num2</th>
    <th>os</th>
    <th>num3</th>
    <th>bool</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <th>0</th>
    <td>2018-04-21</td>
    <td>pandas</td>
    <td>153.474246</td>
    <td>mysql</td>
    <td>0.658533</td>
    <td>ios</td>
    <td>74</td>
    <td>True</td>
    </tr>
    <tr>
    <th>1</th>
    <td>2018-04-13</td>
    <td>sas</td>
    <td>199.461669</td>
    <td>sqlite</td>
    <td>0.656985</td>
    <td>windows 7</td>
    <td>11</td>
    <td>False</td>
    </tr>
    <tr>
    <th>2</th>
    <td>2018-06-09</td>
    <td>stata</td>
    <td>12.918608</td>
    <td>oracle</td>
    <td>0.495707</td>
    <td>android</td>
    <td>25</td>
    <td>False</td>
    </tr>
    <tr>
    <th>3</th>
    <td>2018-04-24</td>
    <td>spss</td>
    <td>88.562111</td>
    <td>sql server</td>
    <td>0.113580</td>
    <td>windows 7</td>
    <td>42</td>
    <td>False</td>
    </tr>
    <tr>
    <th>4</th>
    <td>2018-05-05</td>
    <td>spss</td>
    <td>110.231277</td>
    <td>oracle</td>
    <td>0.660977</td>
    <td>windows 10</td>
    <td>76</td>
    <td>True</td>
    </tr>
    ...
    </tbody>
    </table>
    </body>
    </html>


    HTML Output






    share|improve this answer













    Pandas' to_html simply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the <table> a class attribute that will be referenced in a previously created CSS document that styles it. Therefore, incorporate to_html into a wider HTML document build that references an external CSS.



    Interestingly, to_html adds dual classes <table class="dataframe mystyle"> which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data.



    Data



    import pandas as pd
    import numpy as np

    pd.set_option('display.width', 1000)
    pd.set_option('colheader_justify', 'center')

    np.random.seed(6182018)
    demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
    'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50),
    'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50),
    'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50),
    'num1': np.random.randn(50)*100,
    'num2': np.random.uniform(0,1,50),
    'num3': np.random.randint(100, size=50),
    'bool': np.random.choice([True, False], 50)
    },
    columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
    )


    print(demo_df.head(10))
    # date analysis_tool num1 database num2 os num3 bool
    # 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True
    # 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False
    # 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False
    # 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False
    # 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True
    # 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True
    # 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True
    # 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False
    # 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False
    # 9 2018-04-12 r 38.963967 postgres 0.266604 windows 7 46 False


    CSS (save as df_style.css)



    /* includes alternating gray and white with on-hover color */

    .mystyle {
    font-size: 11pt;
    font-family: Arial;
    border-collapse: collapse;
    border: 1px solid silver;

    }

    .mystyle td, th {
    padding: 5px;
    }

    .mystyle tr:nth-child(even) {
    background: #E0E0E0;
    }

    .mystyle tr:hover {
    background: silver;
    cursor: pointer;
    }


    Pandas



    pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>

    html_string = '''
    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    {table}
    </body>
    </html>.
    '''

    # OUTPUT AN HTML FILE
    with open('myhtml.html', 'w') as f:
    f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))




    OUTPUT



    HTML (references df_style.css, assumed in same directory; see class argument in table)



    <html>
    <head><title>HTML Pandas Dataframe with CSS</title></head>
    <link rel="stylesheet" type="text/css" href="df_style.css"/>
    <body>
    <table border="1" class="dataframe mystyle">
    <thead>
    <tr style="text-align: center;">
    <th></th>
    <th>date</th>
    <th>analysis_tool</th>
    <th>num1</th>
    <th>database</th>
    <th>num2</th>
    <th>os</th>
    <th>num3</th>
    <th>bool</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <th>0</th>
    <td>2018-04-21</td>
    <td>pandas</td>
    <td>153.474246</td>
    <td>mysql</td>
    <td>0.658533</td>
    <td>ios</td>
    <td>74</td>
    <td>True</td>
    </tr>
    <tr>
    <th>1</th>
    <td>2018-04-13</td>
    <td>sas</td>
    <td>199.461669</td>
    <td>sqlite</td>
    <td>0.656985</td>
    <td>windows 7</td>
    <td>11</td>
    <td>False</td>
    </tr>
    <tr>
    <th>2</th>
    <td>2018-06-09</td>
    <td>stata</td>
    <td>12.918608</td>
    <td>oracle</td>
    <td>0.495707</td>
    <td>android</td>
    <td>25</td>
    <td>False</td>
    </tr>
    <tr>
    <th>3</th>
    <td>2018-04-24</td>
    <td>spss</td>
    <td>88.562111</td>
    <td>sql server</td>
    <td>0.113580</td>
    <td>windows 7</td>
    <td>42</td>
    <td>False</td>
    </tr>
    <tr>
    <th>4</th>
    <td>2018-05-05</td>
    <td>spss</td>
    <td>110.231277</td>
    <td>oracle</td>
    <td>0.660977</td>
    <td>windows 10</td>
    <td>76</td>
    <td>True</td>
    </tr>
    ...
    </tbody>
    </table>
    </body>
    </html>


    HTML Output







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 20 '18 at 2:10









    ParfaitParfait

    54.4k104872




    54.4k104872













    • Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

      – sparrow
      Jun 20 '18 at 16:19






    • 2





      I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

      – Parfait
      Jun 20 '18 at 17:11











    • df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

      – sparrow
      Jun 20 '18 at 19:31






    • 1





      Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

      – Parfait
      Jun 20 '18 at 19:38











    • Thanks, I still have a bit to learn ;).

      – sparrow
      Jun 20 '18 at 19:39



















    • Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

      – sparrow
      Jun 20 '18 at 16:19






    • 2





      I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

      – Parfait
      Jun 20 '18 at 17:11











    • df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

      – sparrow
      Jun 20 '18 at 19:31






    • 1





      Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

      – Parfait
      Jun 20 '18 at 19:38











    • Thanks, I still have a bit to learn ;).

      – sparrow
      Jun 20 '18 at 19:39

















    Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

    – sparrow
    Jun 20 '18 at 16:19





    Thanks, it's confusing since one needs to reference the .css file in an "html_string" before using it's classes with "to_html". Seems like there should be a way to specify the .css file from the argument directly.

    – sparrow
    Jun 20 '18 at 16:19




    2




    2





    I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

    – Parfait
    Jun 20 '18 at 17:11





    I think the confusion is really with pandas authors labeling the method to_html() when really it is to_html_table_string(). A full HTML document is not produced with this method and class is a special attribute created in <table> output. Plus, class is not reserved for just CSS but can be used in Javascript/JQuery and others.

    – Parfait
    Jun 20 '18 at 17:11













    df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

    – sparrow
    Jun 20 '18 at 19:31





    df.to_html(myhtml.html) will produce a simple html table of the dataframe that can be opened in a browser. Is that not a "full html document"?

    – sparrow
    Jun 20 '18 at 19:31




    1




    1





    Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

    – Parfait
    Jun 20 '18 at 19:38





    Not it is not. Check page source and you will see <html>, <body>, and other tags are missing even though your browser renders a table.

    – Parfait
    Jun 20 '18 at 19:38













    Thanks, I still have a bit to learn ;).

    – sparrow
    Jun 20 '18 at 19:39





    Thanks, I still have a bit to learn ;).

    – sparrow
    Jun 20 '18 at 19:39













    0














    Here's how I did it



    Create a text file for css code and write down your css code here, say css_style.txt
    Now read this txt file as a string in your python file



    with open('css_style.txt', 'r') as myfile:
    style = myfile.read()



    Now in HTML code



    """<html><head>Something Something</head>{1}<div>{0}</div></html>""".format(some_panda_dataframe.to_html,style)


    Here in my case css_style.txt file is



    <style>
    table {
    border-collapse: collapse;
    width: 100%;
    }

    th {
    text-align: center;
    padding: 8px;
    }

    td {
    text-align: left;
    padding: 8px;
    }

    tr:nth-child(even){background-color: #FFD5D5}

    th {
    background-color: #0000FF;
    color: white;
    }
    </style>





    share|improve this answer




























      0














      Here's how I did it



      Create a text file for css code and write down your css code here, say css_style.txt
      Now read this txt file as a string in your python file



      with open('css_style.txt', 'r') as myfile:
      style = myfile.read()



      Now in HTML code



      """<html><head>Something Something</head>{1}<div>{0}</div></html>""".format(some_panda_dataframe.to_html,style)


      Here in my case css_style.txt file is



      <style>
      table {
      border-collapse: collapse;
      width: 100%;
      }

      th {
      text-align: center;
      padding: 8px;
      }

      td {
      text-align: left;
      padding: 8px;
      }

      tr:nth-child(even){background-color: #FFD5D5}

      th {
      background-color: #0000FF;
      color: white;
      }
      </style>





      share|improve this answer


























        0












        0








        0







        Here's how I did it



        Create a text file for css code and write down your css code here, say css_style.txt
        Now read this txt file as a string in your python file



        with open('css_style.txt', 'r') as myfile:
        style = myfile.read()



        Now in HTML code



        """<html><head>Something Something</head>{1}<div>{0}</div></html>""".format(some_panda_dataframe.to_html,style)


        Here in my case css_style.txt file is



        <style>
        table {
        border-collapse: collapse;
        width: 100%;
        }

        th {
        text-align: center;
        padding: 8px;
        }

        td {
        text-align: left;
        padding: 8px;
        }

        tr:nth-child(even){background-color: #FFD5D5}

        th {
        background-color: #0000FF;
        color: white;
        }
        </style>





        share|improve this answer













        Here's how I did it



        Create a text file for css code and write down your css code here, say css_style.txt
        Now read this txt file as a string in your python file



        with open('css_style.txt', 'r') as myfile:
        style = myfile.read()



        Now in HTML code



        """<html><head>Something Something</head>{1}<div>{0}</div></html>""".format(some_panda_dataframe.to_html,style)


        Here in my case css_style.txt file is



        <style>
        table {
        border-collapse: collapse;
        width: 100%;
        }

        th {
        text-align: center;
        padding: 8px;
        }

        td {
        text-align: left;
        padding: 8px;
        }

        tr:nth-child(even){background-color: #FFD5D5}

        th {
        background-color: #0000FF;
        color: white;
        }
        </style>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 6 at 17:43









        Shubham ChourasiaShubham Chourasia

        1




        1






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50807744%2fapply-css-class-to-pandas-dataframe-using-to-html%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas