Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas rounding decimals not working

Can someone please explain what's happening me or am I missing something really obvious?

import pandas as pd
df = pd.DataFrame([[0.0094909865]])
df = df.round(9)
print(df)

This gives me 0.009490986.

I was expecting a rounded value of 0.009490987

Can someone help me understand? I am using Pandas '0.20.3'

like image 442
Gayathri Avatar asked May 13 '18 21:05

Gayathri


Video Answer


1 Answers

Good question. This is an undocumented quirk. Actually, DataFrame.round uses numpy.around. It should be mentioned in pandas documentation.


The numpy.around() does the following:

For values exactly halfway between rounded decimal values, Numpy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.

See the Reference for more details.

To achieve what you want you can do the following:

from math import ceil, floor
import pandas as pd

df = pd.DataFrame([[0.0094909865]])

def float_round(num, places = 0, direction = floor):
    return direction(num * (10**places)) / float(10**places)

print( float_round(df.values,9,ceil) )
print( float_round(df.values,9) )

print( float_round(1.1389182804 ,9) )

Results

0.009490987
0.009490986

1.13891828
like image 77
seralouk Avatar answered Sep 23 '22 01:09

seralouk