Pandas转字典后出现大量9或0小数尾数的解决方法
在使用Pandas将DataFrame转换为字典时,你可能会遇到浮点数出现大量9或0小数尾数的情况。这是因为在转换过程中,Pandas默认将浮点数转换为numpy.float64类型,而该类型在计算机内部表示时可能会出现精度损失。
为了解决这个问题,你可以选择以下两种方法:
- 使用round方法进行四舍五入
使用round方法可以将浮点数四舍五入到指定的小数位数,例如:
import pandas as pd
df = pd.DataFrame({'A': [1.23456789, 2.34567890], 'B': [3.45678901, 4.56789012]})
# 转换为字典并指定小数位数
d1 = df.round(2).to_dict(orient='list')
print(d1)
# {'A': [1.23, 2.35], 'B': [3.46, 4.57]}
- 使用str方法将浮点数转换为字符串
使用astype(str)方法可以将浮点数转换为字符串,再转换为字典,例如:
import pandas as pd
df = pd.DataFrame({'A': [1.23456789, 2.34567890], 'B': [3.45678901, 4.56789012]})
# 转换为字符串再转换为字典
d2 = df.astype(str).to_dict(orient='list')
print(d2)
# {'A': ['1.23456789', '2.3456789'], 'B': ['3.45678901', '4.56789012']}
你可以根据具体情况选择使用哪种方法。
原文地址: https://www.cveoy.top/t/topic/nuTh 著作权归作者所有。请勿转载和采集!