pandas DataFrame style lost table border

Question:

I’m following instructions at https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
to set up style for my data frame to become html.

It worked well, except that the table’s border of each row/column is lost. It is now a borderless table.

How can I add borders?

Asked By: abisko

||

Answers:

I don’t usually use the pandas style, so I looked it up. The following code will help you. It’s like we have a priority of styles.
The one you set later takes precedence. It seems that you can specify the selector at once, but you need to specify each one.

import numpy as np
import pandas as pd
from IPython.display import display, HTML

df = pd.DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])

style = df.style.set_table_styles(
    [{"selector": "", "props": [("border", "1px solid grey")]},
      {"selector": "tbody td", "props": [("border", "1px solid grey")]},
     {"selector": "th", "props": [("border", "1px solid grey")]}
    ]
)


HTML(style.render())

enter image description here

Answered By: r-beginners

VS Code Specific Answer

In visual studio code notebook editor the accepted answer does not work because the notebook table style has an !important in the existing CSS. (Perhaps caused by the dracula theme I am using, or vs code itself?)

To force it to work I had to modify @r-beginners answer as follows:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])

df.style.set_table_styles(
    [
      {"selector": "td, th", "props": [("border", "1px solid grey !important")]},
    ]
)

screenshot of dataframe output

Notes:

  • I added the !important marker to the css
  • I changed the selector to just "td, th" to style both data and header cells with one line.
  • I don’t explicitly display the result; the dataframe will be rendered because it is the value of the last expression in the cell
Answered By: thehappycheese