如何在python中使用tabulate做小计?

问题描述 投票:1回答:1

我在我的程序中使用tabulate得到如下所示的决策表。我想实现的是得到列和行两边的小计。在python中可以实现吗?

+-------+----------+---------+----------+---------+----------+

| Env   |   xsmall |   small |   medium |   large |   xlarge |

|-------+----------+---------+----------+---------+----------|

| dev   |        2 |       4 |        6 |       1 |        2 |

| prod  |        1 |       9 |        4 |       0 |        0 |

| qa    |        0 |      10 |        1 |       0 |        1 |

| uat   |        0 |       0 |        2 |       0 |        0 |

+-------+----------+---------+----------+---------+----------+

我想得到这样的小计Row 2+4+6+1+2 =15,以此类推Column 2+1+0+0 = 3。

+-------+----------+---------+----------+---------+----------+---------

| Env   |   xsmall |   small |   medium |   large |   xlarge |Sub Total

|-------+----------+---------+----------+---------+----------+----------

| dev   |        2 |       4 |        6 |       1 |        2 |15

| prod  |        1 |       9 |        4 |       0 |        0 |14

| qa    |        0 |      10 |        1 |       0 |        1 |12

| uat   |        0 |       0 |        2 |       0 |        0 |2

+-------+----------+---------+----------+---------+----------+--------
|SubTotal|        3 |       23|        13|       1 |        3|43

将感谢您的帮助

pandas python-2.7 aggregate tabulate
1个回答
0
投票

你可以用以下方法添加行 append 并列有 assign:

df = df.set_index('Env')
new_df = (df.append(df.sum().rename('SubTotal'))
            .assign(SubTotal=lambda x: x.sum(1))
            .reset_index()
         )

产出:

        Env  xsmall  small  medium  large  xlarge  SubTotal
0       dev       2      4       6      1       2        15
1      prod       1      9       4      0       0        14
2        qa       0     10       1      0       1        12
3       uat       0      0       2      0       0         2
4  SubTotal       3     23      13      1       3        43
© www.soinside.com 2019 - 2024. All rights reserved.