如何移除Pandas DataFrame生成的HTML表格左上角的index文本?
解决方案
该问题由透视表的行索引名称、多层列索引的层级名称默认显示在左上角交叉位置导致,你之前调用的行索引相关配置方法未覆盖列层级名称设置,因此不生效。
只需在透视表数据处理完成、调用style方法前,添加两行代码清空所有索引名称即可解决:
# 清空行索引名称 table.index.name = None # 清空多层列索引的所有层级名称 table.columns.names = [None, None]
如果你使用的是Pandas 1.4及以上版本,还可以在Styler调用链中追加以下配置,进一步强制隐藏所有索引名称标识:
.hide(axis='index', names=True) .hide(axis='columns', names=True)
修改后完整代码
df = datasets[9] df.rename(columns={'program': 'Program', 'agent': 'Agent', 'dials': 'Dials','conversations': 'Conversations', 'successes': 'Successes'}, inplace=True) table = pd.pivot_table(df, values=['Dials', 'Successes'], index=['Agent'], columns=['Program'], aggfunc=np.sum, margins=True, margins_name='Total', fill_value=0) table = table.applymap(lambda x: '' if x == 0 else '{:,}'.format(x)) # 新增配置:移除左上角多余索引文本 table.index.name = None table.columns.names = [None, None] mode.export_csv(table, index=False) def hover(hover_color="#ffff00"): return dict(selector="tr:hover", props=[("background-color", "%s" % hover_color)]) table_styles = [ hover(), dict(selector="caption", props=[("caption-side", "bottom")]), dict(selector="") ] table = (table.style.set_table_styles(table_styles) .set_caption("") # 可选配置:Pandas 1.4+ 强制隐藏索引名称 # .hide(axis='index', names=True) # .hide(axis='columns', names=True) ) table
内容的提问来源于stack exchange,提问作者Dan Czarnik
相关产品推荐
相关产品推荐

