Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left align column values in pandas `to_string()`?

I want to save a pandas dataframe to a file with to_string(), but want to left align the column values. With to_string(justify=left), only column labels are left aligned.

For example with

pd.DataFrame({'col1': [' 123 ', ' 1234'], 'col2': ['1', '444441234']}).to_string(index=False)

I get the following result:

enter image description here

I want to get rid of the whitespaces in the first row by left aligning the column values.

like image 234
franco mango Avatar asked Oct 18 '25 12:10

franco mango


1 Answers

The to_string methods provides support for per column formatters. It allows you to use specific formats for all of some columns. A rather simple way is to create a format and then apply it with a lambda. The only picky part is that to use left formatting, you will have to know the width of the column.

For your provided data, you could left align everything with:

df = pd.DataFrame({'col1': ['   123 ', ' 1234'], 'col2': ['1', '444441234']})
widths = [4, 9]
formats = ['{' + f':<{i}' + '}' for i in widths]
print(df.to_string(index=None, col_space=widths, formatters=
                   [(lambda x: fmt.format(x)) for fmt in formats],
                   justify='left'))

to get:

col1       col2      
    123     1        
  1234      444441234

You could also left align only some columns by using a dict for the formatters parameter:

print(df.to_string(index=None, formatters=
                   {'col2': (lambda x: '{:<9}'.format(x))},
                   justify='left'))

gives:

col1     col2      
    123   1        
    1234  444441234
like image 200
Serge Ballesta Avatar answered Oct 21 '25 03:10

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!