如何在Visual Studio Code中单行打印Pandas DataFrame?
解决Pandas DataFrame输出不规整的问题
你可以通过补充设置更多Pandas显示选项来让输出规整:
- 添加
display.width指定输出总宽度,适配你的终端窗口:
pd.set_option('display.width', 1200) # 数值可根据终端实际宽度调整
- 设置
display.max_colwidth限制列内容的最大宽度,避免单列内容过长导致换行:
pd.set_option('display.max_colwidth', 30) # 按需调整截断长度
完整的设置代码:
import pandas as pd pd.set_option('display.max_columns', None) pd.set_option('expand_frame_repr', False) pd.set_option('display.width', 1200) pd.set_option('display.max_colwidth', 30)
如果终端窗口本身宽度不足,先调整终端窗口大小再运行代码。另外如果你的字典数据里包含换行符,需要先清理数据:
# 替换所有字段中的换行符为空格 df = df.replace(r'\n', ' ', regex=True)
也可以直接用to_string()方法强制指定输出格式:
print(df.to_string(width=1200, max_colwidth=30))
内容的提问来源于stack exchange,提问作者KING COBRA
相关产品推荐
相关产品推荐

