Reputation: 751
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)})
but when I try to format the DataFrame I get the basic DataFrame,
df.style.format({
'A': '{:,.2f}'.format,
'B': '{:,.2%}'.format,
})
So how can I change the code so the formated df will appear with the borders one?
Upvotes: 2
Views: 6115
Reputation: 9738
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?
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.
1.- So, given your initial commands:
2.- If you only apply styles on the columns:
3.- If you set properties for the cells:
4.- If you also set table properties, for example, on the th
header elements:
If you want to share these styles among other DataFrames, then take a look at Pandas Styling documentation.
Upvotes: 8