使用pandas.DataFrame.to_csv()按列打印不同的精度? [英] Print different precision by column with pandas.DataFrame.to_csv()?

查看:2732
本文介绍了使用pandas.DataFrame.to_csv()按列打印不同的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以为Python pandas 整批方法 pandas.DataFrame.to_csv

Is it possible to specify a float precision specifically for each column to be printed by the Python pandas package method pandas.DataFrame.to_csv?

如果我有一个 pandas 这样排列:

If I have a pandas dataframe that is arranged like this:

In [53]: df_data[:5]
Out[53]: 
    year  month  day       lats       lons  vals
0   2012      6   16  81.862745 -29.834254   0.0
1   2012      6   16  81.862745 -29.502762   0.1
2   2012      6   16  81.862745 -29.171271   0.0
3   2012      6   16  81.862745 -28.839779   0.2
4   2012      6   16  81.862745 -28.508287   0.0

可以用于指定精度的 float_format 选项,但是在打印时将该精度应用于数据帧的所有列。

There is the float_format option that can be used to specify a precision, but this applys that precision to all columns of the dataframe when printed.

当我这样使用时:

df_data.to_csv(outfile, index=False,
                   header=False, float_format='%11.6f')



我得到以下结果,其中 vals 的精确度不准确:

2012,6,16,  81.862745, -29.834254,   0.000000
2012,6,16,  81.862745, -29.502762,   0.100000
2012,6,16,  81.862745, -29.171270,   0.000000
2012,6,16,  81.862745, -28.839779,   0.200000
2012,6,16,  81.862745, -28.508287,   0.000000


推荐答案

您可以使用 to_string 。有一个 formatters 参数,您可以在其中提供列名称的​​格式化。然后,您可以使用一些regexp将默认列分隔符替换为您选择的分隔符。

You can do this with to_string. There is a formatters argument where you can provide a dict of columns names to formatters. Then you can use some regexp to replace the default column separators with your delimiter of choice.

这篇关于使用pandas.DataFrame.to_csv()按列打印不同的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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