首页 > 解决方案 > 熊猫数据框为总计创建带有水平边框的html表格

问题描述

我想在最后一行上方添加一条水平线。我在下面包含了我的解决方案,但有兴趣了解是否有更好的方法。水平线延伸到索引以覆盖“总计”标签会很好。(我的例子也是行总计 FWIW)

我猜可能可以使用pivot_tableorcrosstab但我不需要额外的聚合;它似乎没有做边界。

谢谢。

标签: pythoncsspandashtml-table

解决方案


这是我正在使用的:

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)

在此处输入图像描述


推荐阅读