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

如何在Pandas中调整DataFrame的行高

你猜测的expand_frame_repr参数仅用于控制超出显示宽度的DataFrame是否自动拆分为多行打印,和行高没有关联。针对不同使用场景,可以参考以下方案调整DataFrame的行高:

场景1:Jupyter Notebook/Lab 环境

这是最常见的需要调整行高做文本比对的场景,可直接通过pandas Styler自定义HTML样式实现:

import pandas as pd

# 示例DataFrame,包含两段待比对的长文本
df = pd.DataFrame({
    "文本列1": ["长文本测试内容1"*6, "长文本测试内容2"*6],
    "文本列2": ["比对文本内容1"*6, "比对文本内容2"*6]
})

# 单独设置当前DataFrame的行高,按需调整line-height后的数值即可
df.style.set_table_styles([
    {"selector": "tr", "props": [("line-height", "80px")]}
])

如果希望全局生效,不用每次单独设置,可以运行全局样式配置:

# 先取消列宽限制,避免长文本被截断
pd.set_option("display.max_colwidth", None)
from IPython.display import HTML
HTML("""
<style>
    .dataframe tbody tr {
        line-height: 80px !important;
    }
</style>
""")

场景2:终端/纯文本输出场景

纯文本打印的行高本质由终端的行间距控制,pandas没有直接调整参数,可通过插入空行模拟增大行高的效果:

# 将DataFrame转为字符串列表,每行对应一个元素
df_lines = df.to_string(index=False).split("\n")
# 隔行插入空行后打印
print("\n\n".join(df_lines))

场景3:导出到Excel文件时设置行高

如果需要导出文件后查看,可在写Excel时直接指定行高:

with pd.ExcelWriter("比对结果.xlsx") as writer:
    df.to_excel(writer, sheet_name="比对表", index=False)
    worksheet = writer.sheets["比对表"]
    # 设置表头行高
    worksheet.set_row(0, 35)
    # 设置所有数据行行高
    for row_num in range(1, len(df)+1):
        worksheet.set_row(row_num, 60)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:24:00