如何使用 tabulate 将数字格式化为右对齐并带有千位分隔符?

问题描述 投票:0回答:5

我正在使用制表(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 |
+--------+-----------------+
python python-3.x tabulate
5个回答
5
投票

我猜

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

4
投票

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

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

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


1
投票

tabulate

的用法
tabulate(
    tabular_data, 
    headers, tablefmt, 
    floatfmt, 
    numalign,  # ---> here
    stralign, 
    missingval, 
    showindex, 
    disable_numparse, 
    colalign, 
    maxcolwidths
)

因此,要使数字向左对齐,您可以使用

numalign="left"


0
投票

如果您想在表格之外实现数字的右对齐和千位分隔符,您可以简单地使用内置的格式化程序

f".."
。 (参考https://www.pythoncheatsheet.org/cheatsheet/string-formatting

右对齐是通过

实现的
f"{your_number:11d}

示例:

f"£{250:11d}"  will display as  £        250
f"£{1400:11d}" will display as  £       1400

0
投票

也许还不算太晚:

ftable = []
for row in df:
    frow = [f"{num:,}".replace(",", " ") if isinstance(num, int) else num for num in row]
    ftable.append(frow)
print(tabulate(ftable))
© www.soinside.com 2019 - 2024. All rights reserved.