gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:59:28 26 4
gpt4 key购买 nike

我有一个 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 ) 但它将格式应用于所有列中的值。而在您的情况下,您需要为每一列设置不同的格式。

关于python - 在带有尾随零的列中写入 pandas 数据帧 to_csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com