You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Streamlit中让DataFrame多级索引列显示为合并单元格?

解决Streamlit中多级列索引重复显示的问题

当用Streamlit的st.dataframe()展示带有多级列索引(MultiIndex)的DataFrame时,第一级列索引会重复显示,无法实现Python终端打印时的合并单元格效果。以下是针对该问题的两种解决方案:

问题重现代码

import pandas as pd
import numpy as np
import streamlit as st

arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=[None, "Brand"])
df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)

st.dataframe(df)  # 第一级列索引会重复显示,不符合预期

解决方案1:静态合并表格(使用pandas Styler)

利用pandas的Styler生成带合并单元格的HTML表格,通过st.markdown()渲染,实现和终端一致的合并效果:

import pandas as pd
import numpy as np
import streamlit as st

arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=[None, "Brand"])
df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)

# 生成带合并多级列的HTML,设置第一级列标题居中
styled_html = df.style.set_table_styles(
    [{'selector': 'th.col_heading.level0', 'props': [('text-align', 'center')]}]
).to_html(escape=False)

# 渲染HTML表格
st.markdown(styled_html, unsafe_allow_html=True)

注意:此方法生成的是静态表格,不具备st.dataframe()的排序、筛选等交互功能。

解决方案2:交互式合并表格(使用streamlit-aggrid)

如果需要保留表格的交互能力,可以使用streamlit-aggrid组件,它原生支持多级列索引的合并显示:

  1. 先安装依赖:
pip install streamlit-aggrid
  1. 实现代码:
import pandas as pd
import numpy as np
import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder

arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=[None, "Brand"])
df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)

# 配置表格选项,启用交互功能
gb = GridOptionsBuilder.from_dataframe(df)
gb.configure_default_column(groupable=True, editable=True)
grid_options = gb.build()

# 渲染交互式表格
AgGrid(df, gridOptions=grid_options, enable_enterprise_modules=True)

内容的提问来源于stack exchange,提问作者Chronicles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:20:52