0

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.

AndrewK
  • 27
  • 6

1 Answers1

-1

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
aerijman
  • 2,522
  • 1
  • 22
  • 32
  • are you not doing the same mistake that I earlier did – Divyessh Aug 17 '20 at 13:29
  • @Divyessh, `round(20.253500,3) = 20.253`. `np.round(20.253500,3) = 20.254`. So, **NO**, I am not doing the same mistake. – aerijman Aug 17 '20 at 14:32
  • @AndrewK, please, check this answer, since it has been _wrongly_ voted down. Thank you! – aerijman Aug 17 '20 at 14:33
  • Sorry, been away testing this but gave it a tick now. One thing. np.round in your solution doesn't round 0.0005 correctly to 3dp. Rounds it down rather than up. Other than that it works fine. Any ideas why? and how to correct this? – AndrewK Aug 26 '20 at 11:02