-1
excel = pd.read_csv("EH_damages.csv")

Hello! I used the above code to read a csv file into python. However 0.289798953 in original excel changed to 0.289799. Even when I saved the number to text mode in the excel, python still read it as float and the number has fewer digits like 0.289799.

What is wrong with my code? THANKS!!

cs95
  • 379,657
  • 97
  • 704
  • 746

1 Answers1

4

Not all decimals can be exactly represented by floats, but that doesn't seem to be the main issue here. What you are seeing is merely the way Pandas formats DataFrames by default when printed. The actual float stored in the DataFrame may have more digits.

For example, with this DataFrame:

import pandas as pd
df = pd.DataFrame({'foo':[0.289798953]})

You see this:

print(df)
#         foo
# 0  0.289799

But the actual float value is still 0.289798953:

print(df.ix[0, 'foo'])
# 0.289798953

You can tell Pandas to display 9 digits after the decimal point by setting:

pd.options.display.float_format = '{:.9f}'.format

or, as cᴏʟᴅsᴘᴇᴇᴅ suggests, pd.set_option('precision', 9). Then printing the DataFrame shows:

print(df)
#           foo
# 0 0.289798953

You can read more about the available options here.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Probably easier: `pd.set_option('precision', 9)` (or any other number) – cs95 Aug 03 '17 at 00:59
  • @cᴏʟᴅsᴘᴇᴇᴅ: Thanks for the improvement; I didn't know about that. – unutbu Aug 03 '17 at 01:03
  • Yup. Came across the dupe that linked to the [docs](http://pandas.pydata.org/pandas-docs/stable/options.html?highlight=precision#setting-startup-options-in-python-ipython-environment) when looking for an answer to this. – cs95 Aug 03 '17 at 01:04