Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Right-align (pad left) index column in Pandas?

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading