Natasha
Natasha

Reputation: 1521

Precision is lost while reading a column from excel using openpyxl

I'm reading the contents stored in an excel workbook using load_workbook of openpyxl. The following is the code,

wb = load_workbook(filename=xlsx_file, read_only=True, data_only=True )
ws = wb.get_sheet_by_name(name=sheet)
data = ws.values
columns = next(data)[0:]
df = pd.DataFrame(data, columns=columns)

I have a column named t in excel

enter image description here

When I print list(df['t']), I get

[0.0, 0.6, 1.2, 1.7999999999999998, 2.4, 3.0, 3.5999999999999996, 4.2, 4.8, 5.3999999999999995].

I would like to know how to avoid the loss of precision. The same problem occurs when I use

df = pd.read_excel(open(xlsx_file, 'rb'), sheet_name=sheet, index=False)

Upvotes: 3

Views: 927

Answers (1)

gtomer
gtomer

Reputation: 6574

You just need to set the number of digits after the decimal point:

df['t'] = df['t'].map('{:,.1f}'.format)

Upvotes: 1

Related Questions