3

I have a pandas dataframe of floats and wish to write out to_csv, setting whitespace as the delimeter, and with trailing zeros to pad so it is still readable (i.e with equally spaced columns).

The complicating factor is I also want each column to be rounded to different number of decimals (some need much higher accuracy).

To reproduce:

import pandas as pd

df = pd.DataFrame( [[1.00000, 3.00000, 5.00000],
                    [1.45454, 3.45454, 5.45454]] )

df_rounded = df.round( {0:1, 1:3, 2:5} )
df_rounded.to_csv('out.txt', sep=' ', header=False)

Current result for out.txt:

0 1.0 3.0 5.0
1 1.5 3.455 5.45454

Desired:

0 1.0 3.000 5.00000
1 1.5 3.455 5.45454
3
  • DId you try converting the dataframe values to string and then saving it? Commented Oct 31, 2019 at 18:15
  • I think you want something like this: Python Pandas, write DataFrame to fixed-width file (to_fwf?) Commented Oct 31, 2019 at 18:23
  • Best I've got right now: print("\n".join([','.join(line.split()) for line in df_rounded.to_string(index=False).splitlines()])) Commented Oct 31, 2019 at 18:30

1 Answer 1

1

You can get the string representation of the dataframe using df.to_string() (docs). Then simply write this string to a text file.

This method also has col_space parameter to further adjust the spacing between columns.

Example:

with open('out.txt', 'w') as file:
    file.writelines(df_rounded.to_string(header=False))

Outputs:

0  1.0  3.000  5.00000
1  1.5  3.455  5.45454

There is pandas df.to_csv(float_format='%.5f') (more info) but it applies the formatting to values in all columns. Whereas, in your case, you need different formatting for each column.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.