Pandas - 将固定宽度格式行的数据帧写入文件

mca*_*tis 6 python numpy dataframe python-3.x pandas

有一个巨大的 pandas 数据框(df),如下所示:

        id          date      a      b      c
0     0023  201110132120    -30    -45      7
1     0023  201110132130    -30     11   9111
2     0023  201110132140    -24     44    345
3     0023  201110132150    -19    223     11
4     0023  201110132200    -23  -3456  -1250
Run Code Online (Sandbox Code Playgroud)

我需要将此数据帧写入每个字段具有特殊固定宽度的文件中。为此,我使用了 numpy,fe:

np.savetxt('out.txt', df.values, fmt='%+4s %+12s %+5s %+5s %+6s')
Run Code Online (Sandbox Code Playgroud)

那工作还好啊 在这种情况下仅丢失标头。有解决方法吗?

我还用 pandas to_string 函数测试了它:

df.to_string()
Run Code Online (Sandbox Code Playgroud)

但它太慢了。为什么?还有其他选择吗?

Qua*_*ang 2

一种选择是滥用header选项savetxt

formats = '%+4s %+12s %+5s %+5s %+6s'

headers = [format(str(x),y.replace('%+','>')) 
              for x, y in zip(df.columns,formats.split())]

np.savetxt('out.txt', df.values, fmt=formats,
           header=' '.join(headers), comments='')
Run Code Online (Sandbox Code Playgroud)