传统的csv不适合人类阅读,因此,我使用以下命令编写选项卡分隔的熊猫数据格式:
df.to_csv ('output.txt', index = False, header=True, float_format='%.3f', sep='\t')这将产生以下格式的输出:
A B C D
90.856 1.214 0.417 1.858
363.424 0.616 0.302 1.858
1817.121 0.318 0.000 1.858
2180.545 0.296 0.000 1.858但是,我希望输出文件如下所示:
A B C D
90.856 1.214 0.417 1.858
363.424 0.616 0.302 1.858
1817.121 0.318 0.000 1.858
2180.545 0.296 0.000 1.858我不关心列之间有多少空间,但我希望列数据正确地对齐。如何做到这一点?
发布于 2021-05-01 23:45:25
你可以试试np.savetxt
np.savetxt(
r"file.txt",
df.values,
fmt="%-10.3f",
header="".join("{:11}".format(c) for c in df.columns),
comments="",
)保存file.txt
A B C D
90.856 1.214 0.417 1.858
363.424 0.616 0.302 1.858
1817.121 0.318 0.000 1.858
2180.545 0.296 0.000 1.858 发布于 2021-05-01 23:46:35
作为一般提示,有一个__repr__()方法用于将类对象表示为python中的字符串。我们可以在这里用这个特殊的方法来处理数据。
with open('output.txt', 'w') as fo:
fo.write(df.__repr__())https://stackoverflow.com/questions/67351682
复制相似问题