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

Streamlit中st.write()显示Pandas DataFrame内容不全的求助

解决Streamlit展示Pandas DataFrame长字符串换行问题

方案1:优化CSS样式强制换行

你的原有思路方向正确,但可能因Streamlit版本更新导致选择器不匹配,试试更精准的CSS规则,强制单元格内容换行并保留原有换行符:

with st.container():
    st.markdown("""
    <style>
    /* 针对Streamlit数据框的单元格,强制换行 */
    .stDataFrame .cell {
        white-space: pre-wrap !important;
        word-break: break-word;
        max-width: none !important;
    }
    </style>
    """, unsafe_allow_html=True)
    st.dataframe(df_observaciones, width=1500, height=450)
  • white-space: pre-wrap:保留文本中的换行符,同时自动换行超出宽度的内容
  • word-break: break-word:确保长单词也能被拆分换行
  • !important:强制覆盖Streamlit默认的样式规则

方案2:预处理DataFrame中的长字符串

如果CSS调整不生效,可以提前对长字符串列进行预处理,手动添加换行符:

方法A:按固定宽度拆分文本

import textwrap

# 假设目标列名为"content",按每50个字符换行
df_observaciones["content"] = df_observaciones["content"].apply(
    lambda x: textwrap.fill(x, width=50) if isinstance(x, str) else x
)

st.dataframe(df_observaciones, width=1500, height=450)

方法B:替换特定分隔符为换行符

如果文本中有固定分隔符(比如逗号、空格),可以直接替换为换行:

df_observaciones["content"] = df_observaciones["content"].apply(
    lambda x: x.replace(", ", "\n") if isinstance(x, str) else x
)

st.dataframe(df_observaciones, width=1500, height=450)

方案3:使用静态表格展示(备选)

如果不需要交互功能,st.table()默认会自动换行显示长文本:

st.table(df_observaciones)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:35:19