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

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

问题描述

是否可以为要由Python pandas包方法

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的精度不正确:

I get the following, where vals is given an inaccurate precision:

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

推荐答案

在将数据框导出到CSV文件之前,请更改列"vals"的类型

Change the type of column "vals" prior to exporting the data frame to a CSV file

df_data['vals'] = df_data['vals'].map(lambda x: '%2.1f' % x)

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

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

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