pythonbeginner

Pandas Styled DataFrame Report

Apply conditional formatting to a pandas DataFrame for styled HTML reports with highlighting.

python
import pandas as pd

df = pd.DataFrame({'Region':['North','South','East','West'],'Q1':[120,95,110,80],'Q2':[135,102,98,115],'Q3':[140,88,125,107],'Total':[395,285,333,302]})

style = (
    df.style
      .highlight_max(subset=['Q1','Q2','Q3','Total'], color='lightgreen', axis=0)
      .highlight_min(subset=['Q1','Q2','Q3','Total'], color='#ff9999',   axis=0)
      .bar(subset=['Total'], color='#5fba7d')
      .format('{:,.0f}', subset=['Q1','Q2','Q3','Total'])
      .set_caption('Quarterly Sales Report')
)
style.to_excel('report.xlsx', engine='openpyxl')
print('Report saved')

Use Cases

  • executive reporting
  • styled exports
  • BI prototyping

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.