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

如何定位Jupyter Notebook中占用大量空间的输出单元格?

查看Jupyter Notebook各输出单元格大小的方法

方法一:在Notebook内运行代码统计

直接在目标Notebook里新建一个代码单元格,运行以下代码,就能批量统计每个代码单元格的输出大小,还能按体积排序:

import json
import os
from operator import itemgetter

# 替换为你的Notebook文件名,比如"analysis.ipynb"
notebook_path = os.path.abspath("your_notebook.ipynb")
with open(notebook_path, "r", encoding="utf-8") as f:
    nb = json.load(f)

cell_size_list = []
# 遍历所有单元格
for cell_idx, cell in enumerate(nb["cells"], 1):
    # 只处理有输出的代码单元格
    if cell["cell_type"] == "code" and "outputs" in cell and cell["outputs"]:
        # 将输出序列化为字符串,计算字节数并转换为KB
        output_content = json.dumps(cell["outputs"])
        output_size_kb = len(output_content.encode("utf-8")) / 1024
        cell_size_list.append((cell_idx, output_size_kb))

# 按输出大小降序排列,优先定位体积大的单元格
cell_size_list_sorted = sorted(cell_size_list, key=itemgetter(1), reverse=True)

print("各代码单元格输出大小(降序):")
for idx, size in cell_size_list_sorted:
    print(f"单元格 {idx}: {size:.2f} KB")

运行后,你会看到所有带输出的代码单元格的索引和对应的输出体积,直接找到最大的那些单元格即可。

方法二:命令行工具快速统计(适合熟悉终端的用户)

如果你习惯用命令行,可以用jq工具(需提前安装),在终端执行以下命令:

jq '.cells[] | select(.cell_type == "code" and .outputs != []) | {cell_index: [.[]] | index(.), output_size_bytes: (.outputs | tojson | length)}' your_notebook.ipynb

输出结果会显示每个有输出的代码单元格的索引和输出的字节数,除以1024就能得到KB值。

后续优化建议

找到大体积输出单元格后,你可以:

  • 直接清除该单元格的输出(右键单元格 → 清除输出),但会丢失可视化内容;
  • 优先把大体积的matplotlib/seaborn图保存为外部图片文件(比如用plt.savefig("plot.png", dpi=100)降低分辨率),然后在Notebook里用Markdown语法引用:![图标题](plot.png),这样GitHub依然能正常显示图片,同时大幅减小Notebook文件体积。

内容的提问来源于stack exchange,提问作者Tom B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:19:01