Search code examples
pythonpandasdataframeiotostring

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.


Solution

  • 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