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
Mat
  • 1,344
  • 1
  • 9
  • 8
  • DId you try converting the dataframe values to string and then saving it? – Rithin Chalumuri Oct 31 '19 at 18:15
  • I think you want something like this: [Python Pandas, write DataFrame to fixed-width file (to_fwf?)](https://stackoverflow.com/questions/16490261/python-pandas-write-dataframe-to-fixed-width-file-to-fwf) – mermaldad Oct 31 '19 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()]))` – piRSquared Oct 31 '19 at 18:30

1 Answers1

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.

Rithin Chalumuri
  • 1,739
  • 7
  • 19