Gayathri
Gayathri

Reputation: 285

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'

Upvotes: 5

Views: 1480

Answers (1)

seralouk
seralouk

Reputation: 33127

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

Upvotes: 6

Related Questions