'How to align text inside a cell in pandas

If I have a cell containing 2 characters and sometimes 3. I need to format the cell-like:

<2spaces>XX<2spaces>

and if contains 3 characters:

<2spaces>XXX<1space>.

I use a new-style format

dx['C'] = dx['C'].map('{:^4s}'.format)

Note: dx['C'] is a column in pandas table.



Solution 1:[1]

Given:

      C
0   aaa
1    aa

Doing:

df.C = df.C.str.center(6) if len(df.C)%2 else (' ' + df.C).str.center(6)

Output:

        C
0    aaa
1    aa

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1