float64 与 pandas to_csv [英] float64 with pandas to_csv

查看:36
本文介绍了float64 与 pandas 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.0numpy 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 的说明,请参阅 格式规范迷你语言.

For an explanation of %g, see Format Specification Mini-Language.

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

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