Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

pd.DataFrame({
        'ID': {
            0: 11404371006,
            1: 11404371007,
            2: 11404371008,
            3: 11404371009,
            4: 11404371010,
            5: 11404371011
        },
        'TABLE.F1': {
            0: 'Y',
            1: 'NULL',
            2: 'N',
            3: 'N',
            4: 'N',
            5: 'N'
        },
        'O': {
            0: False,
            1: False,
            2: False,
            3: False,
            4: False,
            5: False
        }
    })`enter code here`

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

to_string()

actual output with pd.to_string()

to_csv()

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

>Solution :

Use to_markdown:

out = df.to_markdown(index=False, tablefmt='pipe', colalign=['center']*len(df.columns))
print(out)

# Output:
|     ID      |  TABLE.F1  |   O   |
|:-----------:|:----------:|:-----:|
| 11404371006 |     Y      | False |
| 11404371007 |    NULL    | False |
| 11404371008 |     N      | False |
| 11404371009 |     N      | False |
| 11404371010 |     N      | False |
| 11404371011 |     N      | False |

To remove the second line:

out = out.split('\n')
out.pop(1)
out = '\n'.join(out)
print(out)

# Output
|     ID      |  TABLE.F1  |   O   |
| 11404371006 |     Y      | False |
| 11404371007 |    NULL    | False |
| 11404371008 |     N      | False |
| 11404371009 |     N      | False |
| 11404371010 |     N      | False |
| 11404371011 |     N      | False |
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading