【问题标题】:pandas dataframe create html table with horizontal border for totals熊猫数据框为总计创建带有水平边框的html表格
【发布时间】:2021-02-14 00:09:28
【问题描述】:

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

我猜想pivot_tablecrosstab 可以做到这一点,但我不需要额外的聚合;而且它似乎没有做边框。

谢谢。

【问题讨论】:

    标签: python css pandas html-table


    【解决方案1】:

    这是我正在使用的:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2021-06-02
      相关资源
      最近更新 更多