Search code examples
pythonpandasdataframefixed-width

Saving a Pandas dataframe in fixed format with different column widths


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?


Solution

  • 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)