how to make sure integer part is unchanged when round a float32 with pandas

Viewed 44

here is my code

df = pd.DataFrame([110100.0], dtype=np.float32)
df.round(7)

the result is:

110099.992188

what I expect is 110100.0.

How can I make sure that the round operation only affect decimal part and the integer part remained unchanged

for example: input => expected output

1.0 => 1.0

1.12345678 => 1.1234567

2 Answers

You can use numpy.modf for extract floats to fractional and integral parts and round only fractional part, last add together:

df = pd.DataFrame([110100.0, 1.0, 1.12345678], dtype=np.float32, columns=['col'])

a, b = np.modf(df['col'])
print (b + np.round(a, 7))
0    110100.000000
1         1.000000
2         1.123457
Name: col, dtype: float32

Another solution is multiple by number for round, convert to integer and divide:

val = 10**7
print (df['col'].mul(val).astype(np.int64).div(val))
0    110100.000000
1         1.000000
2         1.123457
Name: col, dtype: float64

Use round function of python and give precision EG:

a = 1.112346789
round(a, 6)
1.112347

round(a, 1)
1.1
Related