如何在Streamlit数据框中高亮指定索引的行?
在Streamlit中高亮CSV指定行的实现方案
核心思路
借助Pandas的style模块自定义行样式,再通过Streamlit渲染带样式的HTML表格。
完整代码示例
import streamlit as st import pandas as pd # 方式1:加载本地CSV文件 # df = pd.read_csv("your_data.csv") # 方式2:通过文件上传组件让用户上传CSV uploaded_file = st.file_uploader("选择CSV文件", type="csv") if uploaded_file is not None: df = pd.read_csv(uploaded_file) # 指定需要高亮的行索引(示例:第0、4、12行) highlight_indices = [0, 4, 12] # 定义高亮样式函数 def highlight_rows(row): # 匹配到目标索引时返回高亮样式,否则返回空样式 if row.name in highlight_indices: # 可自定义样式:背景色、字体加粗、文字颜色等 return ['background-color: #ffff99; font-weight: bold'] * len(row) return [''] * len(row) # 应用样式到DataFrame styled_df = df.style.apply(highlight_rows, axis=1) # 在Streamlit中渲染带样式的表格 st.write(styled_df, unsafe_allow_html=True)
关键细节说明
- 行索引匹配:
row.name对应DataFrame的行索引,确保highlight_indices中的值与实际行索引一致(若使用自定义索引,需同步调整目标值)。 - 样式自定义:可修改返回的CSS样式,比如更换背景色(如
#ffcccc浅红)、调整文字颜色(color: darkblue)等。 - HTML渲染:必须设置
unsafe_allow_html=True,否则Streamlit会原样输出HTML代码,无法展示样式效果。
内容的提问来源于stack exchange,提问作者ThinkHydrogen
相关产品推荐
相关产品推荐

