Skip to main content
 首页 » 编程设计

python之在带有尾随零的列中写入 pandas 数据帧 to_csv

2024年11月01日9java哥

我有一个 float 的 pandas 数据框,希望写出 to_csv,将空格设置为分隔符,并用尾随零填充,以便它仍然可读(即具有等间距的列)。

复杂的因素是我还希望每一列四舍五入到不同的小数位数(有些需要更高的精度)。

重现:

import pandas as pd 
 
df = pd.DataFrame( [[1.00000, 3.00000, 5.00000], 
                    [1.45454, 3.45454, 5.45454]] ) 
 
df_rounded = df.round( {0:1, 1:3, 2:5} ) 
df_rounded.to_csv('out.txt', sep=' ', header=False) 

out.txt 的当前结果:

0 1.0 3.0 5.0 
1 1.5 3.455 5.45454 
 

期望:

0 1.0 3.000 5.00000 
1 1.5 3.455 5.45454 

请您参考如下方法:

您可以使用 df.to_string() ( docs ) 获取数据帧的字符串表示形式。然后只需将此字符串写入文本文件即可。

该方法还有col_space参数进一步调整列间距。

例子:

with open('out.txt', 'w') as file: 
    file.writelines(df_rounded.to_string(header=False)) 

输出:

0  1.0  3.000  5.00000 
1  1.5  3.455  5.45454 

有 pandas df.to_csv(float_format='%.5f') ( more info ) 但它将格式应用于所有列中的值。而在您的情况下,您需要为每一列设置不同的格式。