Jupyter Notebook | 在Notebook中调用自定义模块
遇到的问题:
自定义了一个脚本my_function.ipynb:
def mean(num_list):
return sum(num_list)/len(num_list)
想要在Jupyter Notebook另一个脚本(.ipynb)中调用my_function.ipynb,
import my_function as mf
list_1 = [1,2,3,4,5,6,7,8,9,10]
mean = mf.mean(list_1)
print(mean)
输出:
ModuleNotFoundError: No module named 'my_function'
受阻…
找到的方法:
M1
在Notebook中直接输入:
%run my_function.ipynb
list_1 = [1,2,3,4,5,6,7,8,9,10]
mean = mean(list_1)
print(mean)
输出:
5.5
M2
将my_function保存为.py格式:
然后再上传到Notebook上:
此时便可正常导入:
import my_function as mf
list_1 = [1,2,3,4,5,6,7,8,9,10]
mean = mf.mean(list_1)
print(mean)
输出:
5.5
M3
先在Anaconda Prompt中通过pip安装import_ipynb模块:
然后即可正常import Jupyter Notebook中的.pynb文件了:
import import_ipynb
import my_function as mf
list_1 = [1,2,3,4,5,6,7,8,9,10]
mean = mf.mean(list_1)
print(mean)
输出:
5.5