JavaScript
x
27
27
1
pd.DataFrame({
2
'ID': {
3
0: 11404371006,
4
1: 11404371007,
5
2: 11404371008,
6
3: 11404371009,
7
4: 11404371010,
8
5: 11404371011
9
},
10
'TABLE.F1': {
11
0: 'Y',
12
1: 'NULL',
13
2: 'N',
14
3: 'N',
15
4: 'N',
16
5: 'N'
17
},
18
'O': {
19
0: False,
20
1: False,
21
2: False,
22
3: False,
23
4: False,
24
5: False
25
}
26
})`enter code here`
27
I have the above data frame and would like to save the output in a file as a pipe delimited data like below.
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()
to_csv()
Advertisement
Answer
Use to_markdown
:
JavaScript
1
13
13
1
out = df.to_markdown(index=False, tablefmt='pipe', colalign=['center']*len(df.columns))
2
print(out)
3
4
# Output:
5
| ID | TABLE.F1 | O |
6
|:-----------:|:----------:|:-----:|
7
| 11404371006 | Y | False |
8
| 11404371007 | NULL | False |
9
| 11404371008 | N | False |
10
| 11404371009 | N | False |
11
| 11404371010 | N | False |
12
| 11404371011 | N | False |
13
To remove the second line:
JavaScript
1
14
14
1
out = out.split('n')
2
out.pop(1)
3
out = 'n'.join(out)
4
print(out)
5
6
# Output
7
| ID | TABLE.F1 | O |
8
| 11404371006 | Y | False |
9
| 11404371007 | NULL | False |
10
| 11404371008 | N | False |
11
| 11404371009 | N | False |
12
| 11404371010 | N | False |
13
| 11404371011 | N | False |
14