Skip to content

Commit e1d0119

Browse files
author
Jessica Oraegbu
committed
DOC: Add floating point precision on writing/reading to csv (#13159) guidance
1 parent 22bae73 commit e1d0119

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

doc/source/user_guide/io.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1671,6 +1671,42 @@ function takes a number of arguments. Only the first is required.
16711671
* ``chunksize``: Number of rows to write at a time
16721672
* ``date_format``: Format string for datetime objects
16731673

1674+
Floating Point Precision on Writing and Reading to CSV Files
1675+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1676+
1677+
Floating Point Precision inaccuracies when writing and reading to CSV files happen due to how the numeric data is represented and parsed in pandas.
1678+
During the write process, pandas converts all the numeric values into text that is stored as bytes in the CSV file. However, when we read the CSV back, pandas parses those
1679+
text values and converts them back into different types (floats, integers, strings) which is when the loss of float point precision happens.
1680+
The conversion process is not always guaranteed to be accurate because small differences in data representation between original and reloaded data frame can occur leading to precision loss.
1681+
1682+
* ``float_format``: Format string for floating point numbers
1683+
``df.to_csv('file.csv', float_format='%.17g')`` allows for floating point precision to be specified when writing to the CSV file. In this example, this ensures that the floating point is written in this exact format of 17 significant digits (64-bit float).
1684+
1685+
``df = pd.read_csv('file.csv', float_precision='round_trip')`` allows for floating point precision to be specified when reading from the CSV file. This is guaranteed to round-trip values after writing to a file and Pandas will read the numbers without losing or changing decimal places.
1686+
1687+
.. ipython:: python
1688+
import pandas as pd
1689+
import os
1690+
1691+
x0 = 18292498239.824
1692+
df1 = pd.DataFrame({'One': [x0]}, index=["bignum"])
1693+
1694+
df1.to_csv('test.csv', float_format='%.17g')
1695+
df2 = pd.read_csv('test.csv', index_col=0, float_precision='round_trip')
1696+
1697+
x1 = df1['One'][0]
1698+
x2 = df2['One'][0]
1699+
1700+
print("x0 = %f; x1 = %f; Are they equal? %s" % (x0, x1, (x0 == x1)))
1701+
print("x0 = %f; x2 = %f; Are they equal? %s" % (x0, x2, (x0 == x2)))
1702+
1703+
os.remove('test.csv')
1704+
1705+
.. Output received:
1706+
x0 = 18292498239.824001; x1 = 18292498239.824001; Are they equal? True
1707+
x0 = 18292498239.824001; x2 = 18292498239.824001; Are they equal? True
1708+
..
1709+
16741710
Writing a formatted string
16751711
++++++++++++++++++++++++++
16761712

0 commit comments

Comments
 (0)