【精心解读】关于Jupyter Notebook的28个技巧

时间:2022-04-25
本文章向大家介绍【精心解读】关于Jupyter Notebook的28个技巧,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Jupyter具有很强的可扩展性,支持许多编程语言,可以很容易地托管在计算机上或几乎所有的服务器上,只需要拥有ssh或http访问权限。 最重要的是,它是完全免费的。

在Jupyter中使用Python时,使用了IPython内核,这使得我们可以在Jupyter笔记本中轻松访问IPython功能(后面会介绍更多内容!)

1、键盘快捷键

正如任何用户所知,键盘快捷键会为您节省大量的时间。 Jupyter在顶部的菜单下面保存一keybord快捷键列表:Help > Keyboard Shortcuts,或者在命令模式下按H键。 每次更新Jupyter都值得检查一下,因为所有的时候都会添加更多的快捷方式。

另一种访问键盘快捷方式的方法,以及学习它们的方便方法是使用:Cmd + Shift + P(或者在Linux和Windows上使用Ctrl + Shift + P)。 此对话框可帮助你按名称运行任何命令 - 如果你不知道某个操作的键盘快捷方式,或者您想要执行的操作没有键盘快捷键,则可以使用该对话框。 这个功能类似于Mac上的Spotlight搜索,一旦你开始使用它,你会会知道你的生活从此不能没有它!

The command palette

  • Esc将带你进入命令模式,你可以使用箭头键在笔记本上导航。
  • 在命令模式下:
    • A在当前单元格上方插入一个新单元格,B在下面插入一个新单元格。
    • M将当前单元格更改为Markdown,Y将其更改回代码
    • D + D(按键两次)删除当前单元格
  • Enter将把你从命令模式转换回给定单元格的编辑模式。
  • Shift + Tab会显示刚刚在代码单元中输入的对象的文档字符串(文档) - 你可以继续按下此快捷键以循环使用几种文档模式。
  • Ctrl + Shift + - 会将当前单元格从光标所在的位置分成两部分。
  • Esc + F查找并替换你的代码,而不是输出。
  • Esc + O切换单元格输出。
  • 选择多个单元格:
    • Shift + J或Shift + Down选择向下的下一个sell。你也可以使用Shift + K或Shift + Up选择向上的sell。
    • 选中单元格后,可以删除/复制/剪切/粘贴/批处理。当你需要移动笔记本的某些部分时,这非常有用。
    • 你也可以使用Shift + M来合并多个单元格。

合并多个单元格

2、完美的显示变量

第一部分是广为人知的。 通过完成Jupyter单元格的变量名称或未指定的语句输出,Jupyter将显示该变量,而不需要打印语句。 这在处理Pandas DataFrames时特别有用,因为输出整齐地格式化为表格。

但是很少人知道,你可以修改ast_note_interactivity内核选项来使jupyter对它自己的行上的任何变量或语句执行此操作,所以你可以同时看到多个语句的值。

from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = "all"
from pydataset import dataquakes = data('quakes')quakes.head()quakes.tail()

如果要为Jupyter(Notebook和Console)的所有实例设置此行为,只需使用下面的行创建〜/ .ipython / profile_default / ipython_config.py文件即可。

c = get_config()# Run all nodes interactivelyc.InteractiveShell.ast_node_interactivity = "all"

3、易于链接到文档

在“帮助”菜单中,您可以找到包含NumPy,Pandas,SciPy和Matplotlib等通用库的在线文档的便捷链接。

另外不要忘记,通过在库中添加库,方法或变量。

?str.replace()
Docstring:S.replace(old, new[, count]) -> strReturn a copy of S with all occurrences of substringold replaced by new.  If the optional argument count isgiven, only the first count occurrences are replaced.Type:      method_descriptor

4、绘图

  • matplotlib,用%matplotlib inline激活 。(https://matplotlib.org/)
  • %matplotlib提供交互性,但可能有点慢,因为渲染是在服务器端完成的。
  • Seaborn建立在Matplotlib之上, 只需通过导入Seaborn,你的matplotlib就会变得更漂亮,不需要修改任何代码。(http://seaborn.pydata.org/)
  • mpld3为matplotlib代码提供了替代渲染器(使用d3)。 相当不错,虽然不完整。(https://github.com/mpld3/mpld3)
  • bokeh是建立交互式更好选择。(http://bokeh.pydata.org/en/latest/)
  • plot.ly可以提供更好的plots - 这曾经只是一个付费服务,但最近是开源le 。(https://plot.ly/)
  • Altair是一个相对较新的用Python的可视化库。 使用起来非常简单,并且可以制作出非常好看的图,但是定制这些图的能力并不像Matplotlib那样强大。(https://github.com/altair-viz/altair)

5、IPython Magic命令 上面看到的%matplotlib是一个IPython Magic命令的例子。 基于IPython内核,Jupyter可以从IPython内核访问所有的Magics,它可以让你的工作变得更容易!

# This will list all magic commands%lsmagic
Available line magics:%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmodeAvailable cell magics:%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefileAutomagic is ON, % prefix IS NOT needed for line magics.

建议浏览所有IPython Magic命令的文档,因为你会发现一些适合你的工具。(http://ipython.readthedocs.io/en/stable/interactive/magics.html)

6、IPython Magic - %env:设置环境变量

你可以管理Jupyter的环境变量,而无需重新启动Jupyter服务器进程。 有些库(如theano)使用环境变量来控制行为,%env是最方便的方法。

# 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、IPython Magic - %run:执行python代码

%run可以从.py文件中执行python代码,鲜为人知的是,它也可以执行其他jupyter notebooks,相当有用。

请注意,使用%run与导入python模块不同。

# this will execute and show the output from# all code cells of the specified notebook%run ./two-histograms.ipynb

8、IPython Magic - %load:从外部脚本插入代码

这将用外部脚本替换单元格的内容。 你可以使用计算机上的文件作为源,也可以使用URL。

# Before Running%load ./hello_world.py
# After Running# %load ./hello_world.pyif __name__ == "__main__":  print("Hello World!")
Hello World!

9、IPython Magic - %store:在笔记本之间传递变量

%store命令可以让你在两个不同的文件之间传递变量。

data = 'this is the string I want to pass to different notebook'%store datadel data # This has deleted the variable
Stored 'data' (str)

new

%store -r dataprint(data)
this is the string I want to pass to different notebook

10、IPython Magic - %who:列出全局范围的所有变量

没有任何参数的%who命令将列出全局范围中存在的所有变量。 传递像str这样的参数将仅列出该类型的变量。

one = "for the money"two = "for the show"three = "to get ready now go cat go" %who str
one   three   two

11、IPython Magic - 时间

有两个IPython Magic命令对时间有效 - %%time和%timeit。

%%time会给你关于单元中的代码的单一运行的信息。

%%timeimport timefor _ 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 msWall time: 11.6 s
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

12、IPython Magic - %% writefile和%pycat:导出单元格的内容/显示外部脚本的内容

使用%% writefile magic将该单元格的内容保存到外部文件中。 %pycat会做相反的处理,并显示(在弹出窗口中)外部文件高亮内容。

%%writefile pythoncode.pyimport numpydef 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%pycat pythoncode.py```pythonimport numpydef 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)### 13. IPython Magic - %prun: Show how much time your program spent in each function.Using `%prun statement_name` will give you an ordered table showing you the number of times each internal function was called within the statement, the time each call took as well as the cumulative time of all runs of the function.```python%prun some_useless_slow_function()26324 function calls in 0.556 secondsOrdered by: internal timencalls  tottime  percall  cumtime  percall filename:lineno(function) 10000    0.527    0.000    0.528    0.000 <ipython-input-46-b52343f1a2d5>: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 <ipython-input-46-b52343f1a2d5>: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 <string>:1(<module>)     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}

14.、IPython Magic - 用%pdb进行调试

Jupyter拥有自己的Python Debugger(pdb)接口。 这使得调试成为可能。

你可以在这里查看a list of accepted commands for pdb here.(https://docs.python.org/3.5/library/pdb.html#debugger-commands)

%pdbdef 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)<ipython-input-24-0f6b26649b2e> in <module>()      5     raise NotImplementedError()      6 ----> 7 pick_and_take()<ipython-input-24-0f6b26649b2e> 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:
> <ipython-input-24-0f6b26649b2e>(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>

15、IPython Magic - 输出Retina notebooks的高分辨率绘图

一行神奇的IPython会给你的Retina屏幕输出双分辨率绘图像,比如Macbook。 注意:下面的例子不会在非视网膜屏幕上渲染。

x = range(1000)y = [i ** 2 for i in x]plt.plot(x,y)plt.show();%config InlineBackend.figure_format = 'retina'plt.plot(x,y)plt.show();

16、阻止最终函数的输出

有时候在最后一行阻止函数的输出是很方便的,例如绘图时。 要做到这一点,你只需在最后添加一个分号。

%matplotlib inlinefrom matplotlib import pyplot as pltimport numpyx = numpy.linspace(0, 1, 1000)**1.5# Here you get the output of the functionplt.hist(x)(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. ]), <a list of 10 Patch objects>)# By adding a semicolon at the end, the output is suppressed.plt.hist(x);

17、执行Shell命令

从 notebook内部执行shell命令很容易。 你可以使用它来检查工作文件夹中可用的数据集:

!ls *.csvnba_2016.csv             titanic.csvpixar_movies.csv         whitehouse_employees.csv
!pip install numpy!pip list | grep pandasRequirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packagespandas (0.18.1)

18、使用LaTeX的公式

当你在Markdown单元格中编写LaTeX时,使用MathJax将其渲染为公式。

$$ P(A mid B) = frac{P(B mid A) , P(A)}{P(B)} $$

19、运行代码从其他内核在notebook中

如果你喜欢,你可以将来自多个内核的代码组合到一个notebook中。

只需在每个单元的开始处使用IPython Magics以及你的内核的名称就可以使用该内核:

  • %%bash
  • %%HTML
  • %%python2
  • %%python3
  • %%ruby
  • %%perl
%%bashfor i in {1..5}do   echo "i is $i"donei is 1i is 2i is 3i is 4i is 5

20、安装Jupyter的其他内核

Jupyter的一个很好的功能是能够运行不同语言的内核。 举个例子,这里是如何获取R内核运行。

简单选项:使用Anaconda安装R内核

如果你使用Anaconda来设置你的环境,那么让R工作非常容易。 在终端上运行下面的代码:

conda install -c r r-essentials

较不容易的选项:手动安装R内核

如果你不使用Anaconda,这个过程会更复杂一些。 首先,如果您尚未安装R,则需要安装R。

完成之后,启动R控制台并运行以下命令:

install.packages(c('repr', 'IRdisplay', 'crayon', 'pbdZMQ', 'devtools'))devtools::install_github('IRkernel/IRkernel')IRkernel::installspec()  # to register the kernel in the current R installation

21、在同一个 notebook中运行R和Python

最好的解决方案是安装rpy2(需要一个R的工作版本),可以很容易地用pip完成:(https://bitbucket.org/)

pip install rpy2%load_ext rpy2.ipython%R require(ggplot2)array([1], dtype=int32)
import pandas as pddf = pd.DataFrame({        'Letter': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],        'X': [4, 3, 5, 2, 1, 7, 7, 5, 9],        'Y': [0, 4, 3, 6, 7, 10, 11, 9, 13],        'Z': [1, 2, 3, 1, 2, 3, 1, 2, 3]    })    %%R -i dfggplot(data = df) + geom_point(aes(x = X, y= Y, color = Letter, size = Z))

22、用其他语言编写函数

有时numpy的速度是不够的,我们需要写一些速度较快的代码。

原则上,你可以在动态库中编译函数并编写Python包装器...

但是,这个无聊的部分应该你做吗?

你可以用cython或者fortran编写函数,直接从python代码中使用。

首先你需要安装:

!pip install cython fortran-magic %load_ext Cython%%cythondef myltiply_by_2(float x):    return 2.0 * x    myltiply_by_2(23.)

个人更喜欢使用fortran,这对于编写数字运算函数非常方便。 更多的使用细节可以在这里找到。(http://arogozhnikov.github.io/2015/11/29/using-fortran-from-python.html)

%load_ext fortranmagic%%fortransubroutine compute_fortran(x, y, z)    real, intent(in) :: x(:), y(:)    real, intent(out) :: z(size(x, 1))    z = sin(x + y)end subroutine compute_fortrancompute_fortran([1, 2, 3], [4, 5, 6])

23、Multicursor支持

Jupyter支持多个Multicursor,类似于Sublime Text。 只需按住Alt键并拖动鼠标即可。

24.、Jupyter-contrib扩展

包括jupyter拼写检查器和代码格式化等。

!pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master!pip install jupyter_nbextensions_configurator!jupyter contrib nbextension install --user!jupyter nbextensions_configurator enable --user

25、从Jupyter中创建一个演示文稿。

Damian Avila's的RISE允许你从现有的笔记本中创建一个PPT风格的演示文稿。(https://github.com/damianavila/RISE)

你可以使用conda安装RISE:

conda install -c damianavila82 rise
# Or alternatively pip:pip install RISE
# And then run the following code to install and enable the extension:
jupyter-nbextension install rise --py --sys-prefixjupyter-nbextension enable rise --py --sys-prefix

26、Jupyter输出系统

笔记本显示为HTML,单元格输出可以是HTML,因此你可以返回几乎任何内容:视频/音频/图像。

在这个例子中,我用我的资料库中的图像扫描文件夹,并显示其缩略图:

import osfrom IPython.display import display, Imagenames = [f for f in os.listdir('../images/ml_demonstrations/') if f.endswith('.png')]for name in names[:5]:    display(Image('../images/ml_demonstrations/' + name, width=100))

我们可以用bash命令创建相同的列表

names = !ls ../images/ml_demonstrations/*.pngnames[:5]['../images/ml_demonstrations/colah_embeddings.png', '../images/ml_demonstrations/convnetjs.png', '../images/ml_demonstrations/decision_tree.png', '../images/ml_demonstrations/decision_tree_in_course.png', '../images/ml_demonstrations/dream_mnist.png']

27、“大数据”分析

查询/处理大数据样本有多种解决方案:

  • ipyparallel(以前的ipython集群)是python中简单的map-reduce的一个好选择。我们用它来并行训练许多机器学习模型(https://github.com/ipython/ipyparallel)
  • pyspark(https://www.cloudera.com/documentation/enterprise/5-5-x/topics/spark_ipython.html)
  • spark-sql magic %% sql(https://github.com/jupyter-incubator/sparkmagic)

28、共享notebook

共享笔记本最简单的方法就是使用笔记本文件(.ipynb),但对于那些不使用Jupyter的用户,有几个选择:

  • Convert notebooks to html file using the File > Download as > HTML Menu option.
  • Share your notebook file with gists or on github, both of which render the notebooks. See this example.
    • If you upload your notebook to a github repository, you can use the handy mybinder service to allow someone half an hour of interactive Jupyter access to your repository.
  • Setup your own system with jupyterhub, this is very handy when you organize mini-course or workshop and don't have time to care about students machines.
  • Store your notebook e.g. in dropbox and put the link to nbviewer. nbviewer will render the notebook from whichever source you host it.
  • Use the File > Download as > PDF menu to save your notebook as a PDF. If you're going this route, I highly recommend reading Julius Schulz's excellent article Making publication ready Python notebooks.
  • Create a blog using Pelican from your Jupyter notebooks.