更改jupyter笔记本中的索引号

Hao*_*ang 4 python jupyter-notebook

我正在使用Jupyter Notebook编写一些教程.但是,我在这里遇到了一个问题.如下图所示,当我对同事的笔记本程序进行更改时,索引不正确.如何改变1,在[2]到[34],[35]中的那些?在此输入图像描述

Mik*_*ler 7

单击菜单Cell- > Run all.这将执行所有单元格,您将获得有序的单元索引号.如果它不是从单元格索引开始1,请先单击Kernel- > Restart并确认重新启动.

  • 没有重新运行一切的任何更简单的方法? (4认同)

Ale*_*rev 6

这个简单的 Python 片段就可以做到

import json

with open(NOTEBOOK_FILE, 'rt') as f_in:
    doc = json.load(f_in)


cnt = 1

for cell in doc['cells']:
    if 'execution_count' not in cell:
        continue

    cell['execution_count'] = cnt

    for o in cell.get('outputs', []):
        if 'execution_count' in o:
            o['execution_count'] = cnt

    cnt = cnt + 1


with open(NOTEBOOK_FILE, 'wt') as f_out:
    json.dump(doc, f_out, indent=1)
Run Code Online (Sandbox Code Playgroud)

(确保笔记本没有在 Jupyter 中运行)

  • 非常有用的片段!你救了我一个项目,该项目的要求是在笔记本上进行一次干净的运行,我不想再花 6 个小时运行,谢谢你的提示!它帮助我更好地了解笔记本电脑的真正含义:) (2认同)