Search code examples
python-3.xpandasmeanseriesmedian

pandas series round down median and mean values


I have a series,

s = pd.Series([1.115,2.337,3.225])
s.mean()

2.2256666666666667

I am wondering how to round the mean() and median() values, so that if the number at the 3rd decimal place is 5, it should round down, so the result should be 2.22 instead of 2.2256666666666667.


Solution

  • numpy.around will round to Nearest Even:

    >>> s = pd.Series([1.115,2.337,3.225])
    >>> s.mean()
    2.2256666666666667
    >>> np.around(s.mean(), decimals=4)
    2.2257
    >>> np.around(s.mean(), decimals=3)
    2.226
    >>> np.around(s.mean(), decimals=2)
    2.23
    

    ...but:

    if the number at the 3rd decimal place is 5, it should round down [...] should be 2.22 instead of 2.2256666666666667.

    This is not just rounding; you get 2.22 only if you truncate to 3 decimal places and then round to two:

    >>> (np.trunc([s.mean() * 1000.]) / 1000.)[0]
    2.225
    >>> (np.around(np.trunc([s.mean() * 1000.]) / 1000., decimals=2))[0]
    2.22