Consider the following simple example:
import pandas as pd
df = pd.DataFrame({'text': ["foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"]})
print(df)
This prints:
$ python3 test.py
text
0 foo
1 bar
2 baz
3 qux
4 quux
5 corge
6 grault
7 garply
8 waldo
9 fred
10 plugh
11 xyzzy
12 thud
Note that the autogenerated index column is printed left-aligned (padded with spaces to right).
How can I make the printout of the autogenerated index column to be right-aligned (padded with spaces to left); that is:
text
0 foo
1 bar
2 baz
3 qux
4 quux
5 corge
6 grault
7 garply
8 waldo
9 fred
10 plugh
11 xyzzy
12 thud
>Solution :
Use str.rjust:
s = df.index.astype(str)
df.index = s.str.rjust(s.str.len().max(), ' ')
Note that the index is now a string, not a number.
Output:
text
0 foo
1 bar
2 baz
3 qux
4 quux
5 corge
6 grault
7 garply
8 waldo
9 fred
10 plugh
11 xyzzy
12 thud