我正在使用制表(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 |
+--------+-----------------+
谢谢,
我猜
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"))
数字都变成了字符串。添加选项:colalign("right", "left")。让我们测试一下这个建议...
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, colalign=("right", "left")))
+-------------+--------+
| size | path |
|-------------+--------|
| 225,612,466 | /etc |
| 66 | /home |
+-------------+--------+
宾果,宾果。它在他们的文档中。
tabulate
tabulate(
tabular_data,
headers, tablefmt,
floatfmt,
numalign, # ---> here
stralign,
missingval,
showindex,
disable_numparse,
colalign,
maxcolwidths
)
因此,要使数字向左对齐,您可以使用
numalign="left"
也许还不算太晚:
ftable = []
for row in df:
frow = [f"{num:,}".replace(",", " ") if isinstance(num, int) else num for num in row]
ftable.append(frow)
prunt(tabulate(ftable))