我正在使用制表符(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 |
+--------+-----------------+
谢谢
答案 0 :(得分:0)
我猜想tabulate
中缺少的参数是numalign="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 |
+--------+-----------+
如果要保留成千上万个分隔符,则必须保留格式并使用stralign
将字符串对齐到正确的位置:
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, stralign="right"))
答案 1 :(得分:0)
数字全部变成字符串。添加选项:colalign(“ right”,“ left”)。让我们测试一下建议...
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, colalign=("right", "left")))
+-------------+--------+
| size | path |
|-------------+--------|
| 225,612,466 | /etc |
| 66 | /home |
+-------------+--------+
宾果,宾果游戏。在他们的文档中。