Home > Mobile >  Format pandas dataframe output into a text file as a table (formatted and aligned to the max length
Format pandas dataframe output into a text file as a table (formatted and aligned to the max length

Time:06-28

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.

to_string()

actual output with pd.to_string()

to_csv()

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

CodePudding user response:

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