You need to enable JavaScript to run this app. 如何在Streamlit中使用Python DataFrame样式设置 现有代码失效怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

如何在Streamlit中使用Python DataFrame样式设置 现有代码失效怎么解决

pandas Styler生成的样式无法直接被Streamlit默认的st.dataframe()交互组件识别,你可以选择以下两种方案实现需求:

方案1:静态表格完美还原样式

如果不需要排序、筛选等交互功能,直接将pandas Styler生成的HTML通过markdown渲染即可1:1还原你定义的所有样式,代码如下:

# 原有样式定义代码不变
th_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  ('font-weight', 'bold'),
  ('color', '#6d6d6d'),
  ('background-color', '#f7ffff')
  ]

td_props = [
  ('font-size', '12px')
  ]

styles = [
  dict(selector="th", props=th_props),
  dict(selector="td", props=td_props)
  ]

df2 = outputdframe.style.set_properties(**{'text-align': 'left'}).set_table_styles(styles)

# 新增渲染逻辑,开启HTML渲染权限
import streamlit as st
st.markdown(df2.to_html(), unsafe_allow_html=True)

方案2:保留交互功能的样式实现

如果需要保留表格的排序、搜索、单元格复制等交互功能,可以通过注入全局自定义CSS+Streamlit原生表格组件实现:

import streamlit as st

# 先注入自定义样式
st.markdown("""
<style>
/* 自定义表头样式 */
.stDataFrame thead tr th {
    font-size: 14px;
    text-align: center;
    font-weight: bold;
    color: #6d6d6d;
    background-color: #f7ffff !important;
}
/* 自定义单元格样式 */
.stDataFrame tbody tr td {
    font-size: 12px;
    text-align: left;
}
</style>
""", unsafe_allow_html=True)

# 直接渲染原生交互表格
st.dataframe(outputdframe, use_container_width=True)

内容的提问来源于stack exchange,提问作者Vishnu Sastry H K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 07:42:03