Home > Blockchain >  Pandas DataFrame styler - How to style pandas dataframe as excel table?
Pandas DataFrame styler - How to style pandas dataframe as excel table?

Time:03-29

enter image description here

How to style the pandas dataframe as an excel table (alternate row colour)?

Sample style:

enter image description here

Sample data:

import pandas as pd
import seaborn as sns

df = sns.load_dataset("tips")

CodePudding user response:

If your final goal is to save to_excel, the only way to retain the styling after export is using the apply-based methods:


  • If you only care about the appearance in Jupyter, another option is to set properties for targeted selectors using df.style.set_table_styles (requires pandas 1.2.0 ):

    # pandas 1.2.0 
    df.style.set_table_styles([
        {'selector': 'tr:nth-child(even)', 'props': css_alt_rows},
        {'selector': 'th', 'props': css_indexes},
    ])
    
  • Related