dataframe为总计创建带有水平边框的html表格

2024-10-05 15:20:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在最后一行上方添加一条水平线。我在下面列出了我的解决方案,但我很想知道是否有更好的方法。将水平线延伸到索引中以覆盖“Total”标签会更好。(我的示例中还包含行总数FWIW)

我猜用pivot_tablecrosstab可以做到这一点,但我不需要额外的聚合;而且它似乎不适用于边界

谢谢


Tags: 方法示例table标签解决方案total边界pivot
1条回答
网友
1楼 · 发布于 2024-10-05 15:20:21

以下是我正在使用的:

import pandas as pd
import numpy as np
from IPython.display import HTML
import functools

def borderTop(strRow, srRow):
    #print(strRow, type(sRow), sRow.name)
    if srRow.name == strRow:
        return [ "border-top: 1pt solid black; font-weight: bold" for sCol in srRow ]
    else:
        return [""] * len(srRow)

np.random.seed(0)  # to make the numbers reproducible
dfBody = pd.DataFrame(np.random.randint(0,10,(5,3)))

# make a column of row totals and append it on the right
srRowTots = dfBody.sum(axis=1).astype(int)
srRowTots.name="Total"
dfBody2 = pd.concat([dfBody, srRowTots], axis=1)

# make a row of column totals and append to the bottom
srColTots = dfBody2.sum().astype(int)
srColTots.name="Total"
dfBodyTots = pd.concat([dfBody2, srColTots.to_frame().T])

# Display it, making the total column and row bold and bordered
dfBodyTots.style\
     .set_properties(subset=['Total'], **{'font-weight': 'bold', "border-left": "1pt solid black"})\
     .apply(functools.partial(borderTop, "Total"), axis=1)

enter image description here

相关问题 更多 >