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

Jupyter Notebook中Pandas长列内容截断显示问题求助

解决Jupyter Notebook中Pandas长文本列自动换行问题

以下几个方法可解决长文本列需横向滚动的显示问题:

  • 方法一:注入自定义CSS样式
    在Jupyter Notebook中新建代码单元格,执行以下魔法命令,强制表格单元格文本自动换行:
%%html
<style>
    .dataframe td, .dataframe th {
        white-space: normal !important;
        word-wrap: break-word;
        max-width: 500px; /* 可按需调整最大宽度,避免单元格过宽 */
    }
</style>

这段CSS会覆盖默认表格样式,让文本在单元格内自动换行,无需横向滚动。

  • 方法二:使用Pandas Styler设置样式
    直接通过Pandas的Styler对象为DataFrame设置换行属性,无需修改全局样式:
# 替换df为你的DataFrame名称
df.style.set_properties(**{
    'white-space': 'pre-wrap',
    'max-width': '500px'
})

pre-wrap会保留文本中的空格格式,同时自动换行,适合需要保留格式的长文本内容。

  • 方法三:手动生成带样式的HTML
    通过to_html转换DataFrame为HTML,再修改单元格样式后显示:
from IPython.display import HTML

# 替换df为你的DataFrame名称
html_table = df.to_html().replace('<td>', '<td style="white-space: normal; max-width: 500px;">')
HTML(html_table)

这个方法直接修改HTML代码,针对性强,不会影响其他表格的显示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:33:18