Skip to content
Advertisement

Format pandas dataframe output into a text file as a table (formatted and aligned to the max length of the data or header (which ever is longer))

JavaScript

I have the above data frame and would like to save the output in a file as a pipe delimited data like below.

Expected Output

So far I have tried pd.to_csv and pd.to_string(), both outputs the data in tabular format however, the data is not aligning to the max length of the column header or the data.

to_string()

actual output with pd.to_string()

to_csv()

when using pd.to_csv(index=False, sep='|',line_terminator='|n')

Advertisement

Answer

Use to_markdown:

JavaScript

To remove the second line:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement