You need to enable JavaScript to run this app. 如何在Streamlit中修改pandas dataframe的行颜色
优惠活动
大模型
产品
解决方案
定价
更多

如何在Streamlit中修改pandas dataframe的行颜色

Streamlit 中将 pandas DataFrame 行设置为黑色的实现方法

方案1:单DataFrame单独设置(推荐,不影响其他组件)

使用 pandas 自带的 Styler 配置样式,仅作用于当前需要修改的 DataFrame,适配性更高:

  • 核心是通过 set_properties 方法配置单元格样式,渲染时开启 unsafe_allow_html=True 让样式生效
    示例代码如下:
import streamlit as st
import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    "序号": [1, 2, 3, 4],
    "内容": ["测试1", "测试2", "测试3", "测试4"],
    "状态": ["成功", "失败", "成功", "成功"]
})

# 若要设置行文字为黑色,使用以下配置
styled_df = df.style.set_properties(**{
    "color": "black",
    # 若你实际需要的是行背景色为黑色,把上面的color换成background-color即可,同时可以加文字颜色为白色避免看不清:
    # "background-color": "black",
    # "color": "white"
})

# 渲染DataFrame
st.dataframe(styled_df, use_container_width=True, unsafe_allow_html=True)

方案2:全局统一设置(适合全应用所有DataFrame生效)

如果需要所有页面的所有DataFrame都统一行样式,可以注入自定义CSS实现:

import streamlit as st
import pandas as pd

# 注入全局样式
st.markdown("""
<style>
/* 配置所有DataFrame的表头、单元格文字为黑色 */
.stDataFrame td, .stDataFrame th {
    color: black !important;
}
/* 如果需要设置行背景色为黑色,用下面的样式即可,注意同步修改文字颜色为白色
.stDataFrame td, .stDataFrame th {
    background-color: black !important;
    color: white !important;
}
*/
</style>
""", unsafe_allow_html=True)

# 后续正常渲染DataFrame即可,无需额外配置
df = pd.DataFrame({
    "序号": [1, 2, 3, 4],
    "内容": ["测试1", "测试2", "测试3", "测试4"]
})
st.dataframe(df, use_container_width=True)

注意事项

  • 如果你使用的是 st.table 组件而非 st.dataframe,只需将CSS选择器中的 .stDataFrame 替换为 .stTable 即可生效
  • pandas Styler 还支持叠加条件格式逻辑,可以实现奇偶行不同样式、满足特定条件的行单独改色等需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:57:03