3

我正在使用制表(https://pypi.org/project/tabulate/),我想用千位分隔符格式化一个数字列并右对齐。这就是我所做的,它没有正确对齐我的列。

import pandas as pd
rom tabulate import tabulate

df = pd.DataFrame([{'size':225612466, 'path': '/etc'}, {'size':66, 'path': '/home'}])
df['size'] = df['size'].apply(lambda x: "{:,}".format(x).rjust(15))
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False))

+--------+-------------+
| path   | size        |
|--------+-------------|
| /etc   | 225,612,466 |
| /home  | 66          |
+--------+-------------+

我希望它是这样的:

+--------+-----------------+
| path   | size            |
|--------+-----------------|
| /etc   |     225,612,466 |
| /home  |              66 |
+--------+-----------------+

谢谢,

4

2 回答 2

2

我猜缺少的参数tabulatenumalign="right",但你必须摆脱手动rjust将值更改为str

import pandas as pd
rom tabulate import tabulate

df = pd.DataFrame([{'size':225612466, 'path': '/etc'}, {'size':66, 'path': '/home'}])
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, numalign="right"))

给出输出:

+--------+-----------+
| path   |      size |
|--------+-----------|
| /etc   | 225612466 |
| /home  |        66 |
+--------+-----------+

如果要保留数千个分隔符,则必须使用以下命令保留格式并将字符串与 rigth 对齐stralign

print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, stralign="right"))
于 2018-11-15T17:23:08.697 回答
1

数字都变成了字符串。添加选项: colalign("right", "left")。让我们测试一下这个建议...

print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, colalign=("right", "left")))
+-------------+--------+
|        size | path   |
|-------------+--------|
| 225,612,466 | /etc   |
|          66 | /home  |
+-------------+--------+

宾果,宾果。在他们的文档中。

于 2020-01-08T18:21:29.787 回答