如何组织你的 jupyter notebook
Table of Contents
在一个 Jupyter Notebook 中引用另一个 Notebook 的 Python 函数或类有以下几种常见方法。选择合适的方法取决于你的需求和项目结构:
方法 1: 使用 import_ipynb 模块
这是专门为导入 Jupyter Notebook 中的代码而设计的方法。
1. 安装 import_ipynb
pip install import-ipynb
2. 导入另一个 Notebook
假设有一个 helper_functions.ipynb,你想在当前 Notebook 中使用它的内容。
import import_ipynb
import helper_functions
# 使用 helper_functions 中定义的函数或类
result = helper_functions.some_function()
my_class = helper_functions.SomeClass()
方法 2: 将 Notebook 转换为 Python 文件
将另一个 Notebook 转换为 .py 文件,然后将其导入。
1. 将 Notebook 转换为 Python 文件
在 Jupyter Notebook 界面中:
• 打开要导入的 Notebook。
• 点击菜单栏中的 File -> Download as -> Python (.py)。
• 例如,保存为 helper_functions.py。
2. 在当前 Notebook 中导入
from helper_functions import some_function, SomeClass
result = some_function()
my_class = SomeClass()
如果 .py 文件和当前 Notebook 不在同一目录,可以添加路径:
import sys
sys.path.append('/path/to/directory')
from helper_functions import some_function
方法 3: 使用 nbconvert 自动生成 Python 文件
使用 nbconvert 工具自动从 Notebook 生成 .py 文件,并动态加载。
1. 安装 nbconvert
pip install nbconvert
2. Notebook 动态转换并导入
!jupyter nbconvert --to script helper_functions.ipynb
from helper_functions import some_function
result = some_function()
方法 4: 使用 exec 动态加载 Notebook
这种方法适用于仅临时导入的场景。
1. 加载 Notebook 的代码
with open('helper_functions.ipynb', 'r') as f:
notebook_content = f.read()
import json
notebook = json.loads(notebook_content)
# 提取代码单元格并执行
for cell in notebook['cells']:
if cell['cell_type'] == 'code':
exec(''.join(cell['source']))
2. 使用导入的函数或类
result = some_function()
my_class = SomeClass()
方法 5: 使用 jupytext 实现同步
将 Notebook 转换为 .py 文件并双向同步。
1. 安装 jupytext
pip install jupytext
2. 同步 Notebook 和 Python 文件
在需要同步的 Notebook 中启用 Jupytext:
• 点击菜单栏 File -> Jupytext -> Pair Notebook with light script。
• 保存时会自动生成 .py 文件。
- 导入生成的 .py 文件
from helper_functions import some_function, SomeClass
result = some_function()
my_class = SomeClass()
最佳实践
- 代码重用性:如果一个 Notebook 包含较多可重用代码,建议提取成独立的 Python 模块。
- 路径管理:将所有 Notebooks 和模块组织在统一的项目结构下,例如:
/project ├── notebooks/ │ ├── main_notebook.ipynb │ ├── helper_notebook.ipynb ├── utils/ │ ├── helper_functions.py └── requirements.txt
在这种结构下,可以轻松管理依赖,并使用模块导入机制。
总结
上述方法各有优劣:
- 临时方案(如 import_ipynb):方便快速实验。
- 正式项目(如生成 .py 文件或用 jupytext):更适合长期维护和协作。
选择合适的方法,可以让你的 Notebook 更加高效、易用和模块化!
Comments |0|
Category: 似水流年