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

如何修改Streamlit中DataFrame的表头行颜色?

解决Streamlit st.data_editor表头列自定义颜色问题

问题原因

st.data_editor不支持直接渲染pandas Styler生成的样式,它有独立的组件渲染逻辑,所以你之前调用filtered_df.style的方式不会生效。

解决方案

下面提供两种可行的实现方式:

方法1:使用column_config参数自定义列表头样式

通过st.data_editor的column_config参数,为每个需要修改颜色的列单独设置header_style,指定背景色等样式。

修改后的完整代码示例:

# Initialize filtered dataframe
filtered_df = result_df
float_cols = filtered_df.select_dtypes(include=['float']).columns
filtered_df[float_cols] = filtered_df[float_cols].fillna(0)
filtered_df[float_cols] = filtered_df[float_cols].apply(lambda col: col.round().astype(int))

# 定义列配置,为指定表头设置颜色
column_config = {
    "Market": st.column_config.TextColumn(
        "Market",
        header_style={"backgroundColor": "#FFE4E1", "color": "#000000"}
    ),
    "Metro Quota": st.column_config.NumberColumn(
        "Metro Quota",
        header_style={"backgroundColor": "#E6F7FF", "color": "#000000"}
    ),
    "Metro BTS": st.column_config.NumberColumn(
        "Metro BTS",
        header_style={"backgroundColor": "#F5FFFA", "color": "#000000"}
    ),
    # 其他列如果不需要自定义,可以不写,会使用默认配置
}

# Display the dataframe with filtering logic
with st.expander("Dataframe", expanded=True):
    if selected_market == "All":
        st.data_editor(
            filtered_df,
            height=350,
            use_container_width=True,
            hide_index=True,
            column_config=column_config  # 应用列配置
        )
    else:
        filtered_df = filtered_df[(filtered_df['Market'] == selected_market) | (filtered_df['Market'] == selected_market + " Total")]
        st.data_editor(
            filtered_df,
            use_container_width=True,
            hide_index=True,
            column_config=column_config  # 应用列配置
        )

# Add a button to save the filtered DataFrame as a CSV file
if st.button('Save Finalized Data'):
    # Save the filtered dataframe (either whole or filtered by the selected market)
    filtered_df.to_excel('finalized_goals.xlsx', index=False)
    st.success('Filtered data has been saved successfully!')

方法2:注入自定义CSS样式

如果需要更灵活的样式控制(比如批量设置或复杂样式),可以通过Streamlit的markdown方法注入自定义CSS,针对特定列的表头设置样式。

示例代码:

# 注入自定义CSS
st.markdown("""
    <style>
        /* 针对Market列表头 */
        [data-testid="stDataEditor"] th[data-colname="Market"] {
            background-color: #FFE4E1 !important;
            color: #000000 !important;
        }
        /* 针对Metro Quota列表头 */
        [data-testid="stDataEditor"] th[data-colname="Metro Quota"] {
            background-color: #E6F7FF !important;
            color: #000000 !important;
        }
        /* 针对Metro BTS列表头 */
        [data-testid="stDataEditor"] th[data-colname="Metro BTS"] {
            background-color: #F5FFFA !important;
            color: #000000 !important;
        }
    </style>
""", unsafe_allow_html=True)

# Initialize filtered dataframe
filtered_df = result_df
float_cols = filtered_df.select_dtypes(include=['float']).columns
filtered_df[float_cols] = filtered_df[float_cols].fillna(0)
filtered_df[float_cols] = filtered_df[float_cols].apply(lambda col: col.round().astype(int))

# Display the dataframe with filtering logic
with st.expander("Dataframe", expanded=True):
    if selected_market == "All":
        st.data_editor(filtered_df, height=350, use_container_width=True, hide_index=True)
    else:
        filtered_df = filtered_df[(filtered_df['Market'] == selected_market) | (filtered_df['Market'] == selected_market + " Total")]
        st.data_editor(filtered_df, use_container_width=True, hide_index=True)

# Add a button to save the filtered DataFrame as a CSV file
if st.button('Save Finalized Data'):
    filtered_df.to_excel('finalized_goals.xlsx', index=False)
    st.success('Filtered data has been saved successfully!')

注意事项

  • 方法1中,不同类型的列(文本、数字等)需要对应使用st.column_config.TextColumn、st.column_config.NumberColumn等类型。
  • 方法2中,data-colname的值要和DataFrame的列名完全一致,包括空格和大小写。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:52:07