Search code examples
pandasscipyroundingstatsmodels

Rounding the numeric output of pandas pivot tables and SciPy's stats.mode


Rather than the mean score displaying as 91.144105, how to display instead 91.1? Rather than the mode score displaying as ([90.0], [77]), how to display instead 90?

code snippet and output:

enter image description here

from scipy import stats, import numpy as np

pd.pivot_table(df_inspections_violations, index= ['ACTIVITY YEAR', 'FACILITY ZIP'], values= "SCORE", 
               aggfunc= ['mean', 'median', stats.mode])

Solution

  • You can use style.format (documentation).

    But you'd better split the mode SCORE column in value and (I guess) index, so that you can use a dictionary to control each single column, for example:

    df = pd.DataFrame({
        'a': np.linspace(0, 1, 7),
        'b': np.linspace(31, 90, 7),
        'c': np.arange(10, 17)
    })
    
    df.style.format({
        'a': "{:.2f}",
        'b': "{:.1f}",
        'c': int,
    })
    

    Output

        a       b       c
    0   0.00    31.0    10
    1   0.17    40.8    11
    2   0.33    50.7    12
    3   0.50    60.5    13
    4   0.67    70.3    14
    5   0.83    80.2    15
    6   1.00    90.0    16