【发布时间】:2021-02-14 00:09:28
【问题描述】:
我想在最后一行上方添加一条水平线。我在下面包含了我的解决方案,但有兴趣了解是否有更好的方法。水平线延伸到索引以覆盖“总计”标签会很好。 (我的例子也做了行总计 FWIW)
我猜想pivot_table 或crosstab 可以做到这一点,但我不需要额外的聚合;而且它似乎没有做边框。
谢谢。
【问题讨论】:
标签: python css pandas html-table
我想在最后一行上方添加一条水平线。我在下面包含了我的解决方案,但有兴趣了解是否有更好的方法。水平线延伸到索引以覆盖“总计”标签会很好。 (我的例子也做了行总计 FWIW)
我猜想pivot_table 或crosstab 可以做到这一点,但我不需要额外的聚合;而且它似乎没有做边框。
谢谢。
【问题讨论】:
标签: python css pandas html-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)
【讨论】: