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

如何限制Python Pandas DataFrame列宽且不截断,实现换行对齐

Fix Pandas DataFrame Wrapped Text Alignment Under Columns

To get long column content to wrap under its original column (instead of spilling to the start of the next line), you need to combine column width limits with custom text formatting. Here's how to do it:

Console/Text Output Solution

If you're printing to the console, use a custom text wrapper to indent wrapped lines so they align under the column:

  1. Import required modules:
import pandas as pd
import textwrap
  1. Define a text wrapping function:
    This function splits long text into lines and indents all lines after the first to match the column's position.
def wrap_and_indent(text, line_width=20, indent_spaces=4):
    if pd.isna(text):
        return ""
    lines = textwrap.wrap(str(text), width=line_width)
    if len(lines) == 1:
        return lines[0]
    # Indent subsequent lines with spaces
    return lines[0] + "\n" + "\n".join([" " * indent_spaces + line for line in lines[1:]])
  1. Apply the formatter to your DataFrame:
# Sample DataFrame
df = pd.DataFrame({
    "column1": ["xxxxxx"],
    "column2": ["yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"]
})

# Set max column width to match your line width
pd.set_option("display.max_colwidth", 20)
# Apply the custom formatter to target columns
formatted_df = df.style.format({"column2": lambda x: wrap_and_indent(x, line_width=20, indent_spaces=4)})

# Print the result
print(formatted_df.to_string())

This will produce output like:

column1 column2
0  xxxxxx yyyyyyyyyyyyyyyyyy
           yyyyyyyyyyyyyyyyyy
           yyyyyyyyyyy

Notebook/HTML Output Solution

If you're working in Jupyter notebooks or need HTML output, use Pandas' Styler with CSS to handle wrapping and alignment:

styled_df = df.style.set_properties(**{
    "white-space": "pre-wrap",  # Enable text wrapping
    "text-align": "left",       # Align text left
    "width": "20ch"             # Set column width to 20 characters
}).set_table_styles([
    {"selector": "th", "props": [("text-align", "left")]}  # Align headers left
])

# Display in Jupyter
styled_df

Key Fixes to Your Original Settings

Your original display.max_colwidth = None disables wrapping entirely—setting it to a specific value (like 20) tells Pandas when to wrap text. The custom formatter ensures wrapped lines stay under their column instead of jumping to the start of the row.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:12:44