Python Pandas,将DataFrame写入固定宽度的文件(to_fwf?) [英] Python Pandas, write DataFrame to fixed-width file (to_fwf?)

查看:179
本文介绍了Python Pandas,将DataFrame写入固定宽度的文件(to_fwf?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I see that Pandas has read_fwf, but does it have something like DataFrame.to_fwf? I'm looking for support for field width, numerical precision, and string justification. It seems that DataFrame.to_csv doesn't do this. numpy.savetxt does, but I wouldn't want to do:

numpy.savetxt('myfile.txt', mydataframe.to_records(), fmt='some format')

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

That just seems wrong. Your ideas are much appreciated.

推荐答案

直到有人实现在熊猫中,您可以使用制表包:

Until someone implements this in pandas, you can use the tabulate package:

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

这篇关于Python Pandas,将DataFrame写入固定宽度的文件(to_fwf?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆