Home > front end >  Pad spaces to header row to same as column width Pandas Dataframe
Pad spaces to header row to same as column width Pandas Dataframe

Time:07-25

I have converted csv file to psv file, how can I add spaces using Pandas Dataframe to individual header rows to fix the width of each column.(Widths for columns are 16,56,56,42,6,3 respectively) My table now looks like this I want pad spaces to the header row in the top and also to the row number column on the left side. There need not be any name to the row number column.

|Address_line_1|Address_line_2|Suburb|Postcode|State
0|8 Rangeview st          |            |Rochedale    |4123   |qld
1|563 Esplanade           |Retreat     |Urangan      |4655   |qld
.
.
10|8 Byambee               |            |Harlin       |4740   |qld 

Expected output should be like:

     |Address_line_1      |Address_line_2              |Suburb          |Postcode|State
0    |8 Rangeview st      |                            |Rochedale       |4123    |qld
1    |563 Esplanade       |                            |Urangan         |4655    |qld
.
.
10   |8 Byambee           |                            |Harlin          |4740    |qld  

CodePudding user response:

From my answer, you can use to_markdown:

widths = [16, 56, 56, 42, 6, 3]
df.columns = [c.strip().ljust(w) for c, w in zip(df.columns, widths[1:])]
df.index.name = ''.ljust(widths[0])
out = df.astype(str).to_markdown(tablefmt='pipe', colalign=['left']*len(df.columns))

Then:

out = out.split('\n')
out.pop(1)
out = '\n'.join(l[2:-1] for l in out)
print(out)

Output:

                   | Address_line_1                                             | Address_line_2                                             | Suburb                                       | Postcode   | State   
0                  | 8 Rangeview st                                             |                                                            | Rochedale                                    | 4123       | qld     
1                  | 563 Esplanade                                              | Retreat                                                    | Urangan                                      | 4655       | qld     
10                 | 8 Byambee                                                  |                                                            | Harlin                                       | 4740       | qld     
  • Related