pandas默认只显示DataFrame前10行和后10行,中间省略;需用pd.set_option("max_rows", N)调整,同时设置ast_node_interactivity="all"才能显示所有表达式结果。

输出被截断、显示省略号?先确认是不是 pd.DataFrame 的行数限制
这不是 Jupyter 自身的限制,而是 pandas 默认只显示前 10 行、后 10 行,中间用 ... 省略。运行 df.head() 或直接输入 df 时出现这种现象,本质是 pandas 的显示配置在起作用。
解决方法很简单:在任意 cell 中运行:
import pandas as pd
pd.set_option("max_rows", 100)常用组合(建议一起设):
-
pd.set_option("max_rows", 200)—— 最多显示 200 行(设为None表示不限制) -
pd.set_option("max_columns", 50)—— 防止列也被截断 -
pd.set_option("display.width", 120)—— 控制单行字符宽度,避免换行混乱
想让所有 notebook 一劳永逸生效?改 ipython_config.py
每次新开 notebook 都重输 pd.set_option 太麻烦。永久生效要改 IPython 配置文件:
路径(macOS / Linux):~/.ipython/profile_default/ipython_config.py
路径(Windows):C:\Users\{username}\.ipython\profile_default\ipython_config.py
如果文件不存在,就新建一个,写入:
c = get_config()
c.InteractiveShell.ast_node_interactivity = "all"
pd.set_option("max_rows", 200)
pd.set_option("max_columns", 50)注意:pd 必须提前 import,所以更稳妥写法是:
c = get_config()
c.InteractiveShell.ast_node_interactivity = "all"
<h1>在配置里执行初始化代码</h1><p>c.InteractiveShellApp.exec_lines = [
"import pandas as pd",
"pd.set_option('max_rows', 200)",
"pd.set_option('max_columns', 50)",
]保存后重启 Jupyter Notebook 才生效。
输出带滚动条?那是 Jupyter 的 OutputArea 限制,不是行数问题
如果你看到的是一个带垂直滚动条的小窗口(哪怕只输出 3 行),说明触发了 Jupyter 的输出区域自动滚动策略,和 max_rows 无关。这是前端渲染行为,由 IPython.OutputArea 控制。
临时关闭滚动(当前 notebook 有效):
%%javascript
IPython.OutputArea.prototype._should_scroll = function(){ return false; }或更稳妥地在 Python cell 里运行:
from IPython.display import Javascript
display(Javascript("""
IPython.OutputArea.prototype._should_scroll = function(){ return false; };
"""))这个改动只影响当前 session,刷新页面就失效。真正持久化需要改前端配置或用自定义 CSS,但多数人没必要——Cell → Current Outputs → Toggle 点一下最直接。
为什么改了 max_rows 还是只显示一行?检查 ast_node_interactivity
Jupyter 默认只显示 cell 中最后一个表达式的值,比如:
df.head(3) df.shape "done"
默认只输出 "done"。这不是显示限制,是执行模式问题。
必须设成:
from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"
这样三行都会输出。这个设置和 pd.set_option 是两件事:一个管“输出哪些表达式”,一个管“每个表达式怎么渲染”。漏掉前者,后者再大也只显示最后一行结果。
容易忽略的点:这个配置必须在 cell 里显式运行,或写进 ipython_config.py 的 exec_lines;单纯在 notebook 开头 import pandas 并 set_option 是不够的。


















