Jupyter Notebook的奇妙使用

这篇文章将简单记录Jupyter Notebook的一些进阶使用

快捷键

Shift+Enter:运行本行cell代码并跳转至下一行。
Control+Enter:运行本行cell代码并停在本行。
Tab:自动补全。
Shift+Tab:查看相关函数说明;连敲两次获得详细说明。

Magic 关键字

代码计时

%%timeit
from math import sqrt

def fibol(n):
    if n == 0 :
        return 0
    elif n == 1 :
        return 1
    return fibol(n-1) + fibol(n-1)

def fibo2(n):
    return((1+sqrt(5)**n-(1-sqrt(5))**n))/(2**n*sqrt(5))
The slowest run took 5.84 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.68 µs per loop

你将看到类似如下的更加详细的信息:

mu is the mean, and sigma is the standard deviation.  This is
slightly faster than the normalvariate() function.
%timeit fibol(20)
UsageError: %%timeit is a cell magic, but the cell body is empty. Did you mean the line magic %timeit (single %)?

在notebook中嵌入可视化内容

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,1,300)
for w in range(2,6,2):
    plt.plot(x,np.sin(np.pi*x)*np.sin(2*w*np.pi*x))

在notebook中进行调试

%pdb
Automatic pdb calling has been turned ON
numbers = 'hello'
sum(numbers)

即可进行调试。

转换notebook

在终端输入:

jupyter nbconvert xx.ipynb --to html
jupyter nbconvert xx.ipynb --to markdown
jupyter nbconvert xx.ipynb --to pdf

转换成slides

在`view`中选择
然后在Slide Type中进行选择。
Slides:主slide。
Sub-Slide:子slide,在展示时使用向下的箭头显示出来。
Fragments:最初是隐藏的,当你按下时会出现。
Skip:跳过该cell。
Notes:备注。

选择好之后,还要使用jupyter nbconvert将文件转换成slides。

jupyter nbconvert xx.ipynb --to slides post serve

大功告成!