I am conscious this is a popular query but I haven't found anything on here that quite matches what I need. I have a column in a table that is rounding 36.25 to 36.2 rather than 36.3. Having read about this extensively on here I appreciate the details, however this doesn't help me solve my problem. How can I create some code that will round my 'Outcome' column as I wish please? This code produces a version of the df I am using:
import pandas as pd
import numpy as np
raw_data = {'AreaCode' : ['101', '102', '103', '104'],
'Numerator' : [300, 500, 600, 667],
'Denominator' : [1000, 780, 1100, 1840]}
Data = pd.DataFrame(raw_data, columns = ['AreaCode', 'Numerator', 'Denominator'])
And then i am trying to add an 'Outcome' column:
Data['Outcome'] = Data['Numerator'] / Data['Denominator'] * 100
Produces table below:
AreaCode|Numerator|Denominator|Outcome
101|300|1000|30.000000
102|500|780|64.102564
103|600|1100|54.545455
104|667|1840|36.25000
Which is fine except when I apply Data = Data.round(1)
to this, it rounds 36.250000 to 36.2. I need this column to 1dp showing as 36.3 but how can I code this in Python. Examples on here of how to do this use strings of one-off, user-entered numbers, rather than an entire df.column. It won't let me pass my df.column into these. One example I tried which didn't work:
import math
def my_round(n, ndigits):
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)
return part / (10 ** ndigits