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

如何设置pandas DataFrame打印时自动截断过长的列字符?

解决方法

你要找的配置项是display.max_colwidth,这个参数用于控制DataFrame单列显示的最大字符数,超出长度的内容会自动截断并在末尾补充省略号。
你可以直接把这个参数加到你现有的pd.option_context上下文管理器里即可,比如要截断为前20个字符,修改后的代码如下:

with pd.option_context('expand_frame_repr', True, 'display.max_colwidth', 20):
    print("Trips_with_service_days (mit Fahrplantagen)")
    print(trips_with_service_days.head()[['trip_id', 'service_id', 'start_date', 'end_date', 'fahrplantage_ohne_ausfaelle']])

补充说明

  • 如果你需要不同列用不同的截断长度,或者不想修改全局显示配置,也可以单独对长字段列做切片处理,仅在打印时生成截断后的副本,不会修改原始数据:
    # 仅trip_id列截断为前10个字符,其他列保留原长度
    print_df = trips_with_service_days.head().copy()
    print_df['trip_id'] = print_df['trip_id'].str.slice(0, 10)
    print(print_df[['trip_id', 'service_id', 'start_date', 'end_date', 'fahrplantage_ohne_ausfaelle']])
    
  • display.max_colwidth默认值为50,你之前搜到的「打印不截断DataFrame」的方案,本质就是把这个参数设置为None。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:36:04