以具有不同列宽的固定格式保存 Pandas 数据框 [英] Saving a Pandas dataframe in fixed format with different column widths

查看:192
本文介绍了以具有不同列宽的固定格式保存 Pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 Pandas 数据框 (df):

I have a pandas dataframe (df) that looks like this:

   A   B  C
0  1  10  1234
1  2  20  0

我想以固定格式保存此数据框.我想到的固定格式具有不同的列宽,如下所示:

I want to save this dataframe in a fixed format. The fixed format I have in mind has different column width and is as follows:

A 列的值一个空格,然后一个逗号,B 列的值用四个空格,一个逗号,C 列的值用五个空格"

"one space for column A's value then a comma then four spaces for column B's values and a comma and then five spaces for column C's values"

或象征性地:

-,----,-----

我上面的数据框 (df) 以我想要的固定格式如下所示:

My dataframe above (df) would look like the following in my desired fixed format:

1,  10, 1234
2,  20,    0

如何在 Python 中编写将我的数据帧保存为这种格式的命令?

How can I write a command in Python that saves my dataframe into this format?

推荐答案

df['B'] = df['B'].apply(lambda t: (' '*(4-len(str(t)))+str(t)))
df['C'] = df['C'].apply(lambda t: (' '*(5-len(str(t)))+str(t)))
df.to_csv('path_to_file.csv', index=False)

这篇关于以具有不同列宽的固定格式保存 Pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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