与 pandas 一起使用float64 to_csv [英] float64 with pandas to_csv

查看:92
本文介绍了与 pandas 一起使用float64 to_csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取具有以下浮点数的CSV:

I'm reading a CSV with float numbers like this:

Bob,0.085
Alice,0.005

并导入数据框,然后将此数据框写入新位置

And import into a dataframe, and write this dataframe to a new place

df = pd.read_csv(orig)
df.to_csv(pandasfile)

现在,该pandasfile具有:

Bob,0.085000000000000006
Alice,0.0050000000000000001

会发生什么?也许我必须强制转换为float32之类的其他类型?

What happen? maybe I have to cast to a different type like float32 or something?

我正在使用 pandas 0.9.0 numpy 1.6.2 .

推荐答案

如注释中所述,这是一个通用的浮点问题.

As mentioned in the comments, it is a general floating point problem.

但是您可以使用to_csvfloat_format关键字将其隐藏:

However you can use the float_format key word of to_csv to hide it:

df.to_csv('pandasfile.csv', float_format='%.3f')

或者,如果您不希望将0.0001舍入为零:

or, if you don't want 0.0001 to be rounded to zero:

df.to_csv('pandasfile.csv', float_format='%g')

会给您:

Bob,0.085
Alice,0.005

在您的输出文件中.

有关%g的说明,请参见最小格式规范-语言.

这篇关于与 pandas 一起使用float64 to_csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆