Jupyther notebook ,也就是一般说的 Ipython notebook,是一个可以把代码、图像、注释、公式和作图集于一处,从而实现可读性分析的一种灵活的工具。
Jupyter延伸性很好,支持多种编程语言,可以很轻松地安装在个人电脑或者任何服务器上——只要有ssh或者http接入就可以啦。最棒的一点是,它完全免费哦。
Jupyter 界面
默认情况下,Jupyter Notebook 使用Python内核,这就是为什么它原名 IPython Notebook。Jupyter notebook是Jupyter项目的产物——Jupyter这个名字是它要服务的三种语言的缩写:Julia,PYThon和R,这个名字与“木星(jupiter)”谐音。本文将介绍27个轻松使用Jupyter的小窍门和技巧。
1.快捷键
高手们都知道,快捷键可以节省很多时间。Jupyter在顶部菜单提供了一个快捷键列表:Help > Keyboard Shortcuts 。每次更新Jupyter的时候,一定要看看这个列表,因为不断地有新的快捷键加进来。另外一个方法是使用Cmd + Shift + P ( Linux 和 Windows下 Ctrl + Shift + P亦可)调出命令面板。这个对话框可以让你通过名称来运行任何命令——当你不知道某个操作的快捷键,或者那个操作没有快捷键的时候尤其有用。这个功能与苹果电脑上的Spotlight搜索很像,一旦开始使用,你会欲罢不能。
几个我的最爱:
Esc + F 在代码中查找、替换,忽略输出。
Esc + O 在cell和输出结果间切换。
选择多个cell:
Shift + J 或 Shift + Down 选择下一个cell。
Shift + K 或 Shift + Up 选择上一个cell。
一旦选定cell,可以批量删除/拷贝/剪切/粘贴/运行。当你需要移动notebook的一部分时这个很有用。
Shift + M 合并cell.
2.变量的完美显示
有一点已经众所周知。把变量名称或没有定义输出结果的语句放在cell的最后一行,无需print语句,Jupyter也会显示变量值。当使用Pandas DataFrames时这一点尤其有用,因为输出结果为整齐的表格。
鲜为人知的是,你可以通过修改内核选项ast_note_interactivity,使得Jupyter对独占一行的所有变量或者语句都自动显示,这样你就可以马上看到多个语句的运行结果了。
In [1]: from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [2]: from pydataset import data
quakes = data('quakes')
quakes.head()
quakes.tail()
Out[2]:
lat long depth mag stations
1 -20.42 181.62 562 4.8 41
2 -20.62 181.03 650 4.2 15
3 -26.00 184.10 42 5.4 43
4 -17.97 181.66 626 4.1 19
5 -20.42 181.96 649 4.0 11
Out[2]:
lat long depth mag stations
996 -25.93 179.54 470 4.4 22
997 -12.28 167.06 248 4.7 35
998 -20.13 184.20 244 4.5 34
999 -17.40 187.80 40 4.5 14
1000 -21.59 170.56 165 6.0 119
如果你想在各种情形下(Notebook和Console)Jupyter都同样处理,用下面的几行简单的命令创建文件~/.ipython/profile_default/ipython_config.py即可实现:
c = get_config()
# Run all nodes interactively
c.InteractiveShell.ast_node_interactivity = "all"
3.轻松链接到文档
在Help 菜单下,你可以找到常见库的在线文档链接,包括Numpy,Pandas,Scipy和Matplotlib等。
另外,在库、方法或变量的前面打上?,即可打开相关语法的帮助文档。
In [3]: ?str.replace()
Docstring: S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. Type: method_descriptor
4.在notebok里作图
在notebook里作图,有多个选择:
- matplotlib (事实标准)(http://matplotlib.org/),可通过%matplotlib inline 激活,(https://www.dataquest.io/blog/matplotlib-tutorial/) - %matplotlib notebook 提供交互性操作,但可能会有点慢,因为响应是在服务器端完成的。 - mpld3(https://github.com/mpld3/mpld3) 提供matplotlib代码的替代性呈现(通过d3),虽然不完整,但很好。 - bokeh(http://bokeh.pydata.org/en/latest/) 生成可交互图像的更好选择。 - plot.ly(https://plot.ly/) 可以生成非常好的图,可惜是付费服务。
5.Jupyter Magic命令
上文提到的%matplotlib inline 是Jupyter Magic命令之一。
推荐阅读Jupyter magic命令的相关文档
(http://ipython.readthedocs.io/en/stable/interactive/magics.html),它一定会对你很有帮助。下面是我最爱的几个:
6.Jupyter Magic-%env:设置环境变量
不必重启jupyter服务器进程,也可以管理notebook的环境变量。有的库(比如theano)使用环境变量来控制其行为,%env是最方便的途径。
In [55]: # Running %env without any arguments # lists all environment variables # The line below sets the environment # variable OMP_NUM_THREADS %env OMP_NUM_THREADS=4
env: OMP_NUM_THREADS=4
7.Jupyter Magic-%run:运行python代码
%run 可以运行.py格式的python代码——这是众所周知的。不那么为人知晓的事实是它也可以运行其它的jupyter notebook文件,这一点很有用。
注意:使用%run 与导入一个python模块是不同的。
In [56]: # this will execute and show the output from # all code cells of the specified notebook %run ./two-histograms.ipynb
该操作用外部脚本替换当前cell。可以使用你的电脑中的一个文件作为来源,也可以使用URL。
In [ ]: # Before Running %load ./hello_world.py In [61]: # After Running # %load ./hello_world.py if __name__ == "__main__": print("Hello World!")
Hello World!
%store 命令可以在两个notebook文件之间传递变量。
In [62]: data = 'this is the string I want to pass to different notebook' %store data del data # This has deleted the variable
Stored 'data' (str)
现在,在一个新的notebook文档里……
In [1]: %store -r data print(data)
this is the string I want to pass to different notebook
不加任何参数, %who 命令可以列出所有的全局变量。加上参数 str 将只列出字符串型的全局变量。
In [1]: one = "for the money" two = "for the show" three = "to get ready now go cat go" %who str
one three two
有两种用于计时的jupyter magic命令: %%time 和 %timeit.当你有一些很耗时的代码,想要查清楚问题出在哪时,这两个命令非常给力。
仔细体会下我的描述哦。
%%time 会告诉你cell内代码的单次运行时间信息。
In [4]: %%time import time for _ in range(1000): time.sleep(0.01)# sleep for 0.01 seconds
CPU times: user 21.5 ms, sys: 14.8 ms, total: 36.3 ms Wall time: 11.6 s
%%timeit 使用了Python的 timeit 模块,该模块运行某语句100,000次(默认值),然后提供最快的3次的平均值作为结果。
In [3]: import numpy %timeit numpy.random.normal(size=100)
The slowest run took 7.29 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 5.5 µs per loop
使用%%writefile magic可以保存cell的内容到外部文件。 而%pycat功能相反,把外部文件语法高亮显示(以弹出窗方式)。
In [7]: %%writefile pythoncode.py import numpy def append_if_not_exists(arr, x): if x not in arr: arr.append(x) def some_useless_slow_function(): arr = list() for i in range(10000): x = numpy.random.randint(0, 10000) append_if_not_exists(arr, x)
Writing pythoncode.py
In [8]: %pycat pythoncode.py
import numpy def append_if_not_exists(arr, x): if x not in arr: arr.append(x) def some_useless_slow_function(): arr = list() for i in range(10000): x = numpy.random.randint(0, 10000) append_if_not_exists(arr, x)
使用%prun+函数声明会给你一个按顺序排列的表格,显示每个内部函数的耗时情况,每次调用函数的耗时情况,以及累计耗时。
In [47]: %prun some_useless_slow_function()
26324 function calls in 0.556 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.527 0.000 0.528 0.000 :2(append_if_not_exists) 10000 0.022 0.000 0.022 0.000 {method 'randint' of 'mtrand.RandomState' objects} 1 0.006 0.006 0.556 0.556 :6(some_useless_slow_function) 6320 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.556 0.556 :1() 1 0.000 0.000 0.556 0.556 {built-in method exec} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Jupyter 有自己的调试界面The Python Debugger (pdb)(https://docs.python.org/3.5/library/pdb.html),使得进入函数内部检查错误成为可能。
Pdb中可使用的命令见链接(https://docs.python.org/3.5/library/pdb.html#debugger-commands)
In [ ]: %pdb def pick_and_take(): picked = numpy.random.randint(0, 1000) raise NotImplementedError() pick_and_take() Automatic pdb calling has been turned ON --------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) in () 5 raise NotImplementedError() 6 ----> 7 pick_and_take() in pick_and_take() 3 def pick_and_take(): 4 picked = numpy.random.randint(0, 1000) ----> 5 raise NotImplementedError() 6 7 pick_and_take() NotImplementedError: > (5)pick_and_take() 3 def pick_and_take(): 4 picked = numpy.random.randint(0, 1000) ----> 5 raise NotImplementedError() 6 7 pick_and_take() ipdb>
有时候不让末句的函数输出结果比较方便,比如在作图的时候,此时,只需在该函数末尾加上一个分号即可。
In [4]: %matplotlib inline from matplotlib import pyplot as plt import numpy x = numpy.linspace(0, 1, 1000)**1.5 In [5]: # Here you get the output of the function plt.hist(x) Out[5]: (array([ 216., 126., 106., 95., 87., 81., 77., 73., 71., 68.]), array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]), )
In [6]: # By adding a semicolon at the end, the output is suppressed. plt.hist(x);
在notebook内部运行shell命令很简单,这样你就可以看到你的工作文件夹里有哪些数据集。
In [7]: !ls *.csv
nba_2016.csv titanic.csv pixar_movies.csv whitehouse_employees.csv
当你在一个Markdown单元格里写LaTex时,它将用MathJax呈现公式:如
$$ P(A \mid B) = \frac{P(B \mid A) , P(A)}{P(B)} $$
会变成
如果你想要,其实可以把不同内核的代码结合到一个notebook里运行。
只需在每个单元格的起始,用Jupyter magics调用kernal的名称:
%