Search code examples
pythonpython-3.xpandasnumpyfloating-accuracy

Pandas float value issues using loc


This might be an easy one for Pandas users used to float numbers but doing my head in and I honestly will appreciate your advise.

I am unable to retrieve the value I saved into the dataframe when using .loc

Can someone please explain and help resolve? Thanks!

dict = [{'me': 0.094092328767113}]
df = pandas.DataFrame(dict)
df['me']
Out[32]: 
0    0.094092328767113
Name: me, dtype: float64
df.loc[0,'me']
Out[33]: 0.094092328767113001

Solution

  • You can use basic string formatting -

    >>> '{:.15f}'.format(df.loc[0,'me'])
    >>> '0.094092328767113'
    

    This would result in a string data type. Further, you can convert it to float if you need to using numpy as -

    >>> np.float64('{:.15f}'.format(df.loc[0,'me']))
    >>> 0.094092328767113
    

    The final fix boils down to upgrading the version of Pandas and NumPy as confirmed by OP in the comments.