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

如何基于条件为Streamlit的st.data_editor单元格着色?

如何在Streamlit的st.data_editor中基于条件为特定单元格着色

当然可以实现,以下是两种实用的方法来给rating列中值小于2的单元格染成黄色:

方法1:通过column_config结合HTML样式

这种方法直接针对目标列配置条件样式,无需依赖CSS定位,灵活性更高。

import streamlit as st
import pandas as pd

df = pd.DataFrame(
    [
       {"command": "test 1", "rating": 4, "is_widget": True},
       {"command": "test 2", "rating": 1, "is_widget": False},
       {"command": "test 3", "rating": 3, "is_widget": True},
       {"command": "test 4", "rating": 0, "is_widget": False},
   ]
)

edited_df = st.data_editor(
    df,
    column_config={
        "rating": st.column_config.NumberColumn(
            "Rating",
            # 当rating小于2时,给单元格添加黄色背景的HTML样式
            format_func=lambda x: f'<span style="background-color: yellow; padding: 4px;">{x}</span>' if x < 2 else x
        )
    },
    unsafe_allow_html=True  # 必须开启此参数以渲染HTML样式
)

方法2:注入自定义CSS

这种方法通过CSS定位目标单元格,适合不想修改列配置的场景,注意依赖列的位置和单元格内容。

import streamlit as st
import pandas as pd

# 注入自定义CSS样式
st.markdown(
    """
    <style>
    /* 定位第二列(rating列)中值小于2的单元格 */
    .data-editor tbody tr td:nth-child(2):has(div:contains("0")),
    .data-editor tbody tr td:nth-child(2):has(div:contains("1")) {
        background-color: yellow;
    }
    </style>
    """,
    unsafe_allow_html=True
)

df = pd.DataFrame(
    [
       {"command": "test 1", "rating": 4, "is_widget": True},
       {"command": "test 2", "rating": 1, "is_widget": False},
       {"command": "test 3", "rating": 3, "is_widget": True},
       {"command": "test 4", "rating": 0, "is_widget": False},
   ]
)

edited_df = st.data_editor(df)

注意事项

  • 方法1需要Streamlit 1.20及以上版本支持column_config的format_func和unsafe_allow_html参数;
  • 方法2的CSS:has选择器需要现代浏览器支持,若需兼容旧浏览器,可改用其他定位方式;
  • 若你的rating列不是第二列,需要调整CSS中的nth-child(n)参数为对应列的索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:38:11