Jupyter notebook中五個有趣的魔法命令
眾?所周知,Jupyter notebook是一個交互式的Python shell,也就是IPython的封裝版,非常適合用來進(jìn)行數(shù)據(jù)分析和機(jī)器學(xué)習(xí)。
Jupyter notebook中有很多實(shí)用且鮮為人知的功能,可以實(shí)現(xiàn)有趣的操作,這次舉五個簡單的例子。
1. 腳本代碼寫入本地文件
%%file方法可以將腳本代碼寫入本地Py文件。
%%file E:\hello.py
def func_inside_script(x, y):
return x + y
print('Hello World')
2. 執(zhí)行Py文件
在notebook中可以直接執(zhí)行Py文件,通過%run方法來實(shí)現(xiàn)。
%run hello.py
3. 監(jiān)測代碼運(yùn)行時間
可能你的代碼需要精確的時間控制,那么%timeit方法可以幫到你。
%timeit [x**2 for x in range(100)]
4. 使用系統(tǒng)命令行
在windows中,使用命令行需要打開cmd窗口,如果你使用notebook,則可以通過!方法輕松執(zhí)行命令行代碼。
# 新建文件夾
my_dir = 'new_dir'
!mkdir $my_dir
5. 快速debug
bug是讓人頭疼的事,在notebook中可以輕松進(jìn)行debug,使用%debug命令即可。
def some_func():
var = 'hello world'
for i in range(5):
print(i)
i / 0
return 'finished'
%debug
some_func()
Jupyter notebook中還有很多有趣的魔法命令,感興趣可以多摸索下。