python - 熊猫数据框为总计创建带有水平边框的html表格
问题描述
我想在最后一行上方添加一条水平线。我在下面包含了我的解决方案,但有兴趣了解是否有更好的方法。水平线延伸到索引以覆盖“总计”标签会很好。(我的例子也是行总计 FWIW)
我猜可能可以使用pivot_table
orcrosstab
但我不需要额外的聚合;它似乎没有做边界。
谢谢。
解决方案
这是我正在使用的:
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)
推荐阅读
- php - 需要知道鳕鱼的语言
- c# - 在我的 TableAdapter 中使用 If 语句时发生错误
- ruby-on-rails - 如何在使用 rspec 的方法中分配数据虚拟对象
- mysql - 如何在使用 select 的查询中仅获取具有重复值的列中的最后一个结果?
- android - 为什么 Android 主题不适用于单个按钮
- django - 如何使用 django-import export 添加用于导入数据的文件?
- android - 如何在按钮单击时在自定义视图中绘制一个圆圈
- c - c 中指向 r 值的指针赋值
- angular - 构建时间从 3 分钟到大约 70 分钟 - 使用 Angular7 升级
- javascript - Expo/React Native Fetch API 不返回文本/纯文本数据