Python Pandas,将DataFrame写入固定宽度文件(to_fwf?)

jkm*_*acc 13 python fixed-width pandas

我看到熊猫有read_fwf,但它有类似的东西DataFrame.to_fwf吗?我正在寻找对字段宽度,数值精度和字符串对齐的支持.似乎DataFrame.to_csv不这样做. numpy.savetxt是的,但我不想这样做:

numpy.savetxt('myfile.txt', mydataframe.to_records(), fmt='some format')
Run Code Online (Sandbox Code Playgroud)

这似乎是错的.非常感谢您的想法.

Ale*_*uat 8

pandas.DataFrame.to_string()是你所需要的全部。唯一的技巧是如何管理索引。

# Write
# df.reset_index(inplace=True)  # uncomment if the index matters
df.to_string(filepath, index=False)

# Read
df = pd.read_fwf(filepath)
# df.set_index(index_names, inplace=True)  # uncomment if the index matters
Run Code Online (Sandbox Code Playgroud)

如果索引是pandas.Index没有名称的,reset_index()则应将其分配给column "index"。如果它pandas.MultiIndex没有名称,则应将其分配给 columns ["level_0", "level_1", ...]


Mat*_*mer 7

在有人在pandas中实现此功能之前,您可以使用tabulate包:

import pandas as pd
from tabulate import tabulate

def to_fwf(df, fname):
    content = tabulate(df.values.tolist(), list(df.columns), tablefmt="plain")
    open(fname, "w").write(content)

pd.DataFrame.to_fwf = to_fwf
Run Code Online (Sandbox Code Playgroud)


bra*_*dog 5

Python,Pandas:将DataFrame的内容写入文本File

上面的问题回答帮助了我.它不是最好的,但直到to_fwf存在,这将为我做的伎俩......

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
Run Code Online (Sandbox Code Playgroud)

要么

np.savetxt(r'c:\data\np.txt', df.values, fmt='%10.5f')
Run Code Online (Sandbox Code Playgroud)


小智 5

对于每列的自定义格式,您可以设置整行的格式。fmt参数为每一行提供格式

with open('output.dat') as ofile:
     fmt = '%.0f %02.0f %4.1f %3.0f %4.0f %4.1f %4.0f %4.1f %4.0f'
     np.savetxt(ofile, df.values, fmt=fmt)
Run Code Online (Sandbox Code Playgroud)