0

常规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

我不关心列之间有多少空间,但我希望列数据正确对齐。如何做到这一点?

4

3 回答 3

1

写入文件DataFrame.to_string也是一个关闭选项:

import pandas as pd

df = pd.DataFrame({'A': {0: 90.856, 1: 363.424, 2: 1817.121, 3: 2180.545},
                   'B': {0: 1.214, 1: 0.616, 2: 0.318, 3: 0.296},
                   'C': {0: 0.417, 1: 0.302, 2: 0.0, 3: 0.0},
                   'D': {0: 1.858, 1: 1.858, 2: 1.858, 3: 1.858}})

with open('output.txt', 'w') as f:
    f.write(df.to_string(index=False))

输出.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

浮点精度可以通过以下方式控制float_format

with open('output.txt', 'w') as f:
    f.write(df.to_string(index=False, float_format="{:.1f}".format))

输出.txt

     A B C D
  90.9 1.2 0.4 1.9
 363.4 0.6 0.3 1.9
1817.1 0.3 0.0 1.9
2180.5 0.3 0.0 1.9
于 2021-05-02T00:05:52.137 回答
1

你可以试试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-01T23:45:25.640 回答
0

作为一般提示,__repr__()python 中有一种方法用于将类对象表示为字符串。我们可以在此处对数据框使用该特殊方法。

with open('output.txt', 'w') as fo:
    fo.write(df.__repr__())
于 2021-05-01T23:46:35.883 回答