Search code examples
pandasjupyter-notebook

Format pivot table float format after styling


My pivot table has floats as both indices and columns headers. The values are also floats.

Using a style.map the values are conditional formatted. However, after this, the format of the headers changes and pandas ignores any precision setting:

Here is the DataFrame:

enter image description here

And the basic pivot table I want to show - note I set float precision to 2:

enter image description here

Then applying conditional format to the values:

enter image description here

... pandas messsed up the float formatting.

How do I fix the float formatting?


code

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']
)
pd.options.display.float_format = '{:,.2f}'.format
pt = df.pivot_table(index='B', columns='A', values='C')
pt.style.map(lambda x: 'color:red;' if x > 0.2 else None)

Solution

  • 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