考虑以下简单示例:
import pandas as pd
df = pd.DataFrame({'text': ["foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"]})
print(df)
这打印:
$ 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
请注意,自动生成的索引列是左对齐打印的(用空格向右填充)。
如何使自动生成的索引列的打印输出右对齐(用空格向左填充);那就是:
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
用途:
s = df.index.astype(str)
df.index = s.str.rjust(s.str.len().max(), ' ')