3

I'm trying to modify this answer and get more spacing between columns.

import pandas as pd

df = pd.DataFrame({'A': [1,10],
                   'B': ['B','BBBBBB'],
                   'C': [0,1000],
                   'D': ['D','DDDDDD']})

#https://stackoverflow.com/a/5667535/3014199
spacing = dict(selector="table",props=[('border-collapse', 'separate'), 
                                       ('border-spacing',  '100px 500px')])

# Style
result=df.style.set_properties(subset=df.columns[[0,2]], **{'text-align':'right'})\
               .set_properties(subset=df.columns[[1,3]], **{'text-align':'left'})\
               .set_table_styles([spacing])

print(result.render(),file=open('test.html','w'))

But despite ridiculous values, the columns don't seem any further apart.

adding e.g. 'padding-right':'10px', in set_properties seems to work, but I want to do things right.

(Also, how can I suppress the index, it was index=False for .to_html but where to put it here?)

peer
  • 4,171
  • 8
  • 42
  • 73

2 Answers2

4

You have to skip selector="table" to assign properties to <table></table>.

With selector="table" it assign for table inside table <table><table></table></table>.


You can use

result.render(head=[])` 

to skip headers but there is still <thread> which moves other elements when you use 'border-spacing'

Using

dict(selector="thead", props = [('display', 'none')])

you can hide <thread>

You can also use skip head=[] and it will keep headers in file but you will no see them.


import pandas as pd
import webbrowser


df = pd.DataFrame({
        'A': [1, 10],
        'B': ['B', 'BBBBBB'],
        'C': [0, 1000],
        'D': ['D', 'DDDDDD'],
     })

styles = [
    dict(
        props=[
            ('border-collapse', 'separate'), 
            ('border-spacing',  '10px 50px')
        ]
    ),
    dict(
        selector="thead",
        props = [('display', 'none')]
    )
]         

result = df.style.set_properties(subset=df.columns[[0,2]], **{'text-align':'right'})\
               .set_properties(subset=df.columns[[1,3]], **{'text-align':'left'})\
               .set_table_styles(styles)

with open('test.html', 'w') as f:
    f.write(result.render(head=[]))

webbrowser.open('test.html')

BTW: I checked in source code: render() uses template html.tpl. to_html() uses much complex methods to render HTML (ie. it uses class HTMLFormatter).

furas
  • 134,197
  • 12
  • 106
  • 148
1

I prefer to use bootstrap for the spaces

# Creates the dataframe
df = pd.DataFrame(myData)

# Parses the dataframe into an HTML element with 3 Bootstrap classes assigned.
tables=[df.to_html(classes='table table-hover', header="true")]

in this example, I use the class "table table-hover" from Bootstrap

mikesneider
  • 772
  • 2
  • 10
  • 28