在Pandas中使用read-csv时丢失精度

2024-06-16 12:31:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文本文件中有以下格式的文件,我正试图将其读入pandas数据框。

895|2015-4-23|19|10000|LA|0.4677978806|0.4773469340|0.4089938425|0.8224291972|0.8652525793|0.6829942860|0.5139162227|

如您所见,输入文件中的浮点后面有10整数。

df = pd.read_csv('mockup.txt',header=None,delimiter='|')

当我试图将它读入数据帧时,我没有得到最后4个整数

df[5].head()

0    0.467798
1    0.258165
2    0.860384
3    0.803388
4    0.249820
Name: 5, dtype: float64

如何获得输入文件中的完整精度?我有一些矩阵运算需要执行,所以我不能将它转换为字符串。

我发现我必须对dtype做些什么,但我不确定应该在哪里使用它。


Tags: 文件csv数据pandasdfread格式整数
1条回答
网友
1楼 · 发布于 2024-06-16 12:31:52

这只是显示问题,请参见docs

#temporaly set display precision
with pd.option_context('display.precision', 10):
    print df

     0          1   2      3   4             5            6             7   \
0  895  2015-4-23  19  10000  LA  0.4677978806  0.477346934  0.4089938425   

             8             9            10            11  12  
0  0.8224291972  0.8652525793  0.682994286  0.5139162227 NaN    

编辑:(谢谢Mark Dickinson):

Pandas uses a dedicated decimal-to-binary converter that sacrifices perfect accuracy for the sake of speed. Passing float_precision='round_trip' to read_csv fixes this. See the documentation for more.

相关问题 更多 >