jy247
jy247

Reputation: 31

Table level formatting on pandas to html styles

I am producing an HTML email with a table from a pandas dataframe. I am using pandas styling to add CSS to the resultant table, but I can't get the borders of the table to look right. The CSS does not get applied to the table, so my border-collapse tag is ignored and I have individual borders around every cell.

I have examined the HTML generated and there is an id tag associated with the table in the css. This works for selectors targeting td tags but not on the table tag. When I manually remove this id from the HTML the output generated is fine. My question is how to get this effect in python?

I am using python 2.7.2 and pandas 0.23.4

import pandas as pd
df = pd.DataFrame([[1,2,3],[4,-5,6]])
styles = [ {'selector': 'table',
           'props': [('border', '1px solid lightgrey'),
                     ('border-collapse', 'collapse')]},
          {'selector': 'tbody td',
           'props': [('border', '1px solid lightgrey'),
                     ('font-size', '11.5px'),
                     ('font-family', 'arial'),
                     ('text-align', 'center'),
                     ('width', '120')]}
          ]

html = df.style.set_table_styles(styles).render()

actual has #T_094a3270_141f_11e9_99b1_18a905bf8925 table {

<style  type="text/css" >
    #T_094a3270_141f_11e9_99b1_18a905bf8925 table {
    ... params
    }    #T_094a3270_141f_11e9_99b1_18a905bf8925 tbody td {
    ... params
    }</style>  
<table id="T_094a3270_141f_11e9_99b1_18a905bf8925" > 
... etc

expected just has table {

<style  type="text/css" >
    table {
    ... params
    }    #T_094a3270_141f_11e9_99b1_18a905bf8925 tbody td {
    ... params
    }</style>  
<table id="T_094a3270_141f_11e9_99b1_18a905bf8925" > 
... etc

Upvotes: 2

Views: 4376

Answers (3)

Flavien Lambert
Flavien Lambert

Reputation: 810

There is, I think, a small hack to style the table itself. Because pandas adds the ID of the table in front, you can use it to add a style to the ID itself by passing an empty selector like

styles = [{"selector": "", "props": [("border", "1px solid lightgrey")]}]

Upvotes: 1

Kottamasu Ramesh
Kottamasu Ramesh

Reputation: 1

Keep boarder-collapse in selector th and td instead of table. it works.

Upvotes: 0

jy247
jy247

Reputation: 31

I am interested to hear if anyone has an answer to the above, but I have worked around by manually adding the string

<style  type="text/css" >
    table {
          border: 1px solid lightgrey;
          border-collapse: collapse;
</style>  

to the front of my html after creation.

Annoyingly this has no effect in an html email anyway, although in a browser it looks fine.

thanks

Upvotes: 1

Related Questions