Saving a Pandas dataframe in fixed format with different column widths

佐手、 提交于 2021-02-05 11:29:06

问题


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:

"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"

Or symbolically:

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

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

1,  10, 1234
2,  20,    0

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


回答1:


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)


来源:https://stackoverflow.com/questions/50067957/saving-a-pandas-dataframe-in-fixed-format-with-different-column-widths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!