79233509

Date: 2024-11-28 10:49:39
Score: 0.5
Natty:
Report link

Explicitly formatting headers and indices and then to the data

import pandas as pd
df = pd.DataFrame(
    [
        [0.5, 1.5, 0.1], 
        [0.5, 2.5, 0.3], 
        [1.5, 1.5, 0.4], 
        [1.5, 2.5, 0.2]
    ],
    columns=['A', 'B', 'C']
)
pt = df.pivot_table(index='B', columns='A', values='C')
pt.columns = pt.columns.map(lambda x: f"{x:.2f}")  # Format columns to 2 decimals
pt.index = pt.index.map(lambda x: f"{x:.2f}")      # Format index (rows) to 2 decimals

# Apply conditional formatting 
styled_pt = pt.style.map(lambda x: 'color:red;' if x > 0.2 else None)

# Apply float formatting to the data cells 
styled_pt = styled_pt.format("{:.2f}") 

styled_pt

Output

enter image description here

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: samhita