我在我的程序中使用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
将感谢您的帮助
你可以用以下方法添加行 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