在 jupyter notebook 中更改索引号

change index number in jupyter notebook

我正在使用 Jupyter Notebook 编写一些教程。但是,我在这里遇到了一个问题。如下图,我修改同事的notebook程序时,索引不对。如何更改 1, in [2] to in [34], in [35]?

中的那些

单击菜单 Cell --> Run all。这将执行所有单元格,您将获得有序的单元格索引号。如果不是从cell index1开始,先点击Kernel-->Restart确认重新开始。

这个简单的 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)

(确保笔记本不是 运行 在 Jupyter 中)