pandas DataFrame style lost table border
Asked Answered
B

2

5

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?

Beaman answered 12/11, 2020 at 22:33 Comment(0)
H
1

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

Homochromatic answered 13/11, 2020 at 4:26 Comment(0)
R
9

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
Raffle answered 25/7, 2022 at 4:4 Comment(0)
H
1

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

Homochromatic answered 13/11, 2020 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.