A few weeks ago I was provided with a really useful piece of code to help me to round my health data outcomes to 1dp, using the principle of rounding 1.25 to 1.3 (Python 3 doesn't do this as standard). I've unfortunately come across an instance where my newly defined rounding rule isn't working though! Can someone please suggest an amendment to the my_round below please? It's so frustrating as I thought I'd got the perfect solution here.
import pandas as pd
import math
raw_data = {'AreaCode' : ['101', '101', '101'],
'Disaggregation' : ['1864', '65Over', 'Total'],
'Numerator' : [19.0, 82.0, 101.0],
'Denominator' : [24.0, 160.0, 184.0]}
Data = pd.DataFrame(raw_data, columns = ['AreaCode', 'Disaggregation', 'Numerator', 'Denominator'])
def my_round(n, ndigits=1):
try:
part = n * 10 ** ndigits
delta = part - int(part)
# always round "away from 0"
if delta >= 0.5 or -0.5 < delta <= 0:
part = math.ceil(part)
else:
part = math.floor(part)
val = part/(10 ** ndigits)
except ValueError:
val = np.nan
return val
Data['Outcome'] = (Data['Numerator'] / (Data['Denominator'])*100).apply(my_round)
When all this is run you can see that the 65Over outcome has rounded to 51.2 when the calculation is 82.0 / 160.0 * 100 = 51.250000. I have to be certain such instances will output as 51.3 in my published data.