Ran Cohen
Ran Cohen

Reputation: 751

Python Jupyter Notebook styled dataframe with borders

I am using the following code to format the data frame with borders in jupyter

%%HTML
<style type="text/css">
table.dataframe td, table.dataframe th {
    border: 1px  black solid !important;
  color: black !important;
}
</style>

import pandas as pd
import numpy as np

df = pd.DataFrame( data={'A': range(5), 'B':  np.arange(0, 1 , 0.2)})

enter image description here

but when I try to format the DataFrame I get the basic DataFrame,

df.style.format({
    'A': '{:,.2f}'.format,
    'B': '{:,.2%}'.format,
})

enter image description here

So how can I change the code so the formated df will appear with the borders one?

enter image description here

Upvotes: 2

Views: 6115

Answers (1)

Nicol&#225;s Ozimica
Nicol&#225;s Ozimica

Reputation: 9738

Explaining the problem

When you set a style with %%HTML, you're targeting just those HTML elements that match your CSS selector.

When setting a style to a dataframe, and then displaying it in a cell, the HTML Table generated no longer has a HTML Class named dataframe (but a somewhat random ID). That's the reason your %%HTML didn't apply to the output of the styled dataframe.

What to do then?

Possible solution

Setting the styles of the table itself through Pandas:

df.style.set_properties(
    **{'color': 'black !important',
       'border': '1px black solid !important'}
).set_table_styles([{
    'selector': 'th',
    'props': [('border', '1px black solid !important')]
}]).format({
    'A': '{:,.2f}'.format,
    'B': '{:,.2%}'.format,
})

In these lines of code, you're both giving the dataframe an HTML style, and at the same time you're setting a formatting style to its columns.

Important: these two calls, for both style.set_properties and style.format must be chained. Otherwise, only the last one will be used.

Solution: step by step

1.- So, given your initial commands:

Initial commands

2.- If you only apply styles on the columns:

Styles on the columns

3.- If you set properties for the cells:

Properties for the cells

4.- If you also set table properties, for example, on the th header elements:

Also setting table properties, for th


To go further

If you want to share these styles among other DataFrames, then take a look at Pandas Styling documentation.

Upvotes: 8

Related Questions