How to Add Border to Pandas DataFrame ( HTML Table)

This tutorial explains how to add borders to Pandas DataFrame. DataFrame will be rendered as an HTML table with borders.

Adding borders to Pandas DataFrame is very useful when we work with the multi-index

Setup

Suppose we have the next DataFrame:

import pandas as pd

df = pd.DataFrame(
    {"Grade": ["A", "B", "A", "C"]},
    index=[
        ["11", "11", "12", "12"],
        ["21", "22", "21", "22"],
        ["31", "32", "33", "34"]
    ]
)

which looks like:

Grade
11 21 31 A
22 32 B
12 21 33 A
22 34 C

Step 1: Add inner borders to DataFrame

To add inner borders in Pandas we can use the method .style.set_table_styles().

df.style.set_table_styles([{'selector': 'td', 'props': [('font-size', '12pt'),('border-style','solid'),('border-width','1px')]}])

We need to specify 2 values:

  • selector
    • tr - table rows
    • td - table cells
    • th - table headers
  • props
    • border-style - type of table border
    • border-width - border size

As we can see CSS can be applied to Pandas DataFrame. So anything valid as a CSS property can be passed to a DataFrame.

This converts DataFrame to a good looking HTML table with borders.

      Grade time
11 21 31 A 4
22 32 B 5
12 21 33 A 6
22 34 C 3

Step 2: Add outer borders to DataFrame

Outer borders can be added we can be added by same method:

df.style.set_table_styles([{'selector': 'th', 'props': [('font-size', '12pt'),('border-style','solid'),('border-width','1px')]}])

In this case we use the selector - 'th' - in order to add outer borders.

      Grade time
11 21 31 A 4
22 32 B 5
12 21 33 A 6
22 34 C 3

Step 3: Multiple border selectors

We can combine multiple selectors by using comma - 'selector': 'th,td',. So to add borders to the whole DataFrame we can use:

df.style.set_table_styles([{'selector': 'th,td', 'props': [('font-size', '12pt'),('border-style','solid'),('border-width','1px')]}])
      Grade time
11 21 31 A 4
22 32 B 5
12 21 33 A 6
22 34 C 3

Step 4: Table colors and more styles

Adding color is possible by property: background-color. For example:

styler0 = df.style
styler0.set_table_attributes('style="font-size: 25px"')
styler0.set_table_styles([{'selector': '*', 'props':
                          [('color', 'black'),('border-style','solid'),('border-width','1px')]},
                        {'selector': 'th', 'props':
                          [('background-color',  color1)]}])

First we copy the .style object. Then we set the font size for the whole DataFrame.

Next we modify all properties of the table and finally the table borders.

Step 5: DataFrame to HTML code

To get the code from the HTML you can check this article: Render Pandas DataFrame As HTML Table Keeping Style

In short we can use for the DataFrame without styles:

df.to_html()

or render DataFrame as HTML code with styles:

display_html(df._repr_html_())