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

Time:12-16

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.

CodePudding user response:

A workaround might be to justify the strings yourself:

(pd.DataFrame({'col1': ['   123 ', ' 1234'], 'col2': ['1', '444441234']})
   .apply(lambda s: (s:=s.astype(str).str.strip()).str.ljust(s.str.len().max()))
   .to_string(index=False, justify='left')
)

NB. this requires python 3.8 due to the walrus operator, if you have an earlier version, use a function instead.

def ljust(s):
    s = s.astype(str).str.strip()
    return s.str.ljust(s.str.len().max())

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

Output:

col1 col2     
123  1        
1234 444441234

CodePudding user response:

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

CodePudding user response:

To left-align the column values in the output of to_string(), you can use the ljust() method on each column value:

import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})

# Left-align the column values
output = df.to_string(index=False, header=False)
output = '\n'.join([line.ljust(len(line) 1) for line in output.split('\n')])

print(output)

Output:

 1    Alice    25
 2      Bob    30
 3  Charlie    35

Explanation:

  1. We use to_string() to convert the dataframe to a string, with index=False to omit the index and header=False to omit the column labels.
  2. We split the string into lines using split('\n').
  3. We apply ljust() to each line to left-align the values.
  4. We join the lines back into a single string using join().

Note that this solution works if the column values are left-aligned in the original dataframe. If the values are right-aligned or center-aligned, you will need to adjust the padding accordingly.

  • Related