【问题标题】:How to use tabulate to format number with thousand separator and right align如何使用表格格式化带有千位分隔符和右对齐的数字
【发布时间】:2018-11-15 16:14:11
【问题描述】:

我正在使用制表 (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-3.x tabulate


    【解决方案1】:

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

    【讨论】:

    • 但是这个不做千位分隔符。你知道怎么做吗?
    • 我们可以只为一列(大小)设置对齐方式吗?
    • 这真的应该是另一个问题。你应该已经展示了解决问题的一些努力。您可以尝试的一个显而易见的事情是您可以在右侧填充路径,以便它们显示为左对齐。
    • 对不起,我不清楚我的问题。你可以看到我想要的结果,路径是左对齐的,我只想用千位分隔符右对齐我的大小列。这只是示例数据框。我的数据框有更多的列,因此更希望能够调整一列的配置。
    • 那么我想你唯一的选择就是按照我的建议进行 - 手动对齐各个列。但是,您可以选择手动对齐哪些列,其余列使用 tabulate 的参数(例如 10 个字符串列 + 2 个数字 -> 您手动对齐 2 个数字列并使用 stralign="left")。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 2015-02-28
      • 1970-01-01
      • 2013-05-16
      相关资源
      最近更新 更多