如何基于条件为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
相关产品推荐
相关产品推荐

