Search code examples
pythonroundingcalculated-columnsrounding-errorbankers-rounding

Rounding error across all column values in Python


Good afternoon,

I have a useful piece of code copied in below that appears to work on my dummy data, alas it doesn't work across all values as it goes down the column data.

Code is:

import pandas as pd
from decimal import *

Data['Value'] = Data['Value'].map(lambda x: Decimal(x).quantize(Decimal('0.001'), rounding=ROUND_HALF_UP))

Dummy data:

Data = {'Code' : ['1', '2', '3','4','5','6'],
    'Group' : ['a', 'b','c','d','e','f'],
    'Value' : [20.2535, 21.874, 7.6475,101.84556, 209.8625913, 99.7655037]}
       

Data = pd.DataFrame(Data, columns = ['Code', 'Group', 'Value'])

The output works for the first value however, anymore than that rounds down, not up. Can this be resolved because as he code states, I want to round halfs up?

  output:              Expected: 

0     20.253         0     20.254 << This one is incorrect
1     21.874         1     21.874
2      7.647         2      7.648 << This one is incorrect
3    101.846         3    101.846
4    209.863         4    209.863
5     99.766         5     99.766

Any help would be much appreciated. I'm looking for rounding to 3.dp where all values are rounded half up as per excel.

Thank you.


Solution

  • Rounded DOWN (to the 3rd decimal):

    Data.loc[:,'Value'] = np.round(Data['Value'] - 5e-4, 3) 
    

    Rounded UP:

    Data.loc[:,'Value'] = np.round(Data['Value'], 3)
    

    I expect that with all versions of python 5e-4 = 0.0005. If I am wrong, use 0.0005 or 5*10**-4

    Data:

      Code Group       Value
    0    1     a   20.253500
    1    2     b   21.874000
    2    3     c    7.647500
    3    4     d  101.845560
    4    5     e  209.862591
    5    6     f   99.765504
    

    DOWN output:

      Code Group    Value
    0    1     a   20.253
    1    2     b   21.874
    2    3     c    7.647
    3    4     d  101.845
    4    5     e  209.862
    5    6     f   99.765
    

    UP output

      Code Group    Value
    0    1     a   20.254
    1    2     b   21.874
    2    3     c    7.648
    3    4     d  101.846
    4    5     e  209.863
    5    6     f   99.766