Pandas version checks
-
[x] I have checked that this issue has not already been reported.
-
[x] I have confirmed this bug exists on the latest version of pandas.
-
[x] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
df = pd.DataFrame({"x":[0.2617993877991494,0.111111111111111112]}) # two such examples that result in incorrect truncation
df.to_json("out.json",double_precision=15)
df2 = pd.read_json("out.json")
Issue Description
Using the DataFrame.to_json()
method to serialize a DataFrame
can result in lost data when serializing floats, such that the data cannot be recovered when reloading the json file, even when using the maximum allowable double_precision
parameter, at 15.
This is the result of the to_json()
method incorrectly truncating floats when they should instead be reproduced in full. This seems to perhaps even be an intended behaviour, as the default value of the double_precision
parameter is not even 15, but 10, resulting in even further truncation and lost data. This should not be the case, as the output of the json format stores all numbers as text strings, so there is not an inherent loss in data from the format, and a user should reasonably be able to fully retrieve an exact copy of the data they have saved in the json format at a later time.
Expected Behavior
df = pd.DataFrame({"x":[0.2617993877991494,0.111111111111111112]})
df.to_json("out.json",double_precision=15)
df2 = pd.read_json("out.json")
print(df["x"][0],df["x"][1])
# output: 0.2617993877991494 0.11111111111111112
print(df2["x"][0],df2["x"][1])
# expected output: 0.2617993877991494 0.11111111111111112
# actual output: 0.261799387799149 0.11111111111111101
print(df["x"][0]==df2["x"][0])
# expected output: True (as all we have done is saved the data to the json format and reloaded it)
# actual output : False
print(df["x"][1]==df2["x"][1])
# expected output: True (as all we have done is saved the data to the json format and reloaded it)
# actual output : False