Add CSS to Jupyter Notebook with Pandas

Python Methods and Functions

This is what the default datasheet looks like in Jupyter Notebook:

import pandas as pd

 

 

df = pd.DataFrame ({ `A` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ], 

  ` B` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ], 

`C` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ],

`D` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]})

 
df.head ()

Output:

Now let`s try changing the style. We can do this with using the set_table_styles method of the pandas module.

 df.style.set_table_styles () 

Now we need to pass "Selectors" and "props" as an argument to this method, i.e. we need to select the CSS tags of the table (for example, th, td, etc.) and change the values ​​of their properties (for example, background, font-color, font-family, etc.).

So , if we need to change the font family of the text in the table data section, we can do it like this:

df.style.set_table_styles (

 

[{ `selector` : `td` ,

`props` : [( ` font-family` , `Sans-serif` )]},

])

Let`s go trying to add more changes and see the result.

df = pd.DataFrame ({ ` A` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ], 

`B` : [ 1 , 2 3 , 4 , 5 , 6 , 7 , 8 ], 

`C` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ],

`D` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ],

  ` E` : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]})

 

 
df.style.set_table_styles (
[

{ `selector` : `th` ,

`props` : [( ` background` , `# 606060` ), 

( `color` , ` white` ),]},

{ `selector` : `td` ,

`props` : [( `color` , ` blue` )]},

])

Output:

We can also hide index column with hide_index() method hide_index() :

df.style.set_table_styles (
[

  { `selector` : `th` ,

  `props` : [( ` background` , ` # 606060` ), 

  ( ` color` , `yellow` ),]},

  { `selector` : `td` ,

  ` props ` : [( ` color` , `red` )]},

]  
). hide_index ()

Output:





Get Solution for free from DataCamp guru