Jupyter 笔记本
Jupyter notebook,以前称为 IPython notebook,是一种灵活的工具,可帮助您创建可读的分析,因为您可以将代码、图像、注释、公式和绘图保存在一起。在这篇博文中,我们收集了一些重要的 Jupyter Notebook 技巧,可帮助您快速成为 Jupyter 高级用户!
(这篇文章基于最初出现在 Alex Rogozhnikov 的博客上的一篇文章,“大错特错”。我们已经扩展了这篇文章,并将随着时间的推移继续这样做 - 如果您有任何建议,请告诉我们。感谢 Alex 的慷慨解囊让我们在这里重新发布他的作品。)
Jupyter 具有很强的可扩展性,支持多种编程语言,并且可以轻松托管在您的计算机或几乎任何服务器上——您只需要具有 ssh 或 http 访问权限。最重要的是,它是完全免费的。现在让我们深入了解 28 个(还在增加!)Jupyter Notebook 提示的列表!
Jupyter 界面。
项目 Jupyter 诞生于 IPython 项目,因为该项目发展成为一个可以支持多种语言的笔记本——因此它的历史名称为 IPython 笔记本。Jupyter 这个名字是它设计的三种核心语言的间接首字母缩写词:JU lia、PYT hon 和R,其灵感来自木星行星。
在 Jupyter 中使用 Python 时,会使用 IPython 内核,这使我们可以从 Jupyter 笔记本中方便地访问 IPython 功能(稍后会详细介绍!)
我们将向您展示 28 个提示和技巧,让您使用 Jupyter 的生活更轻松。
1. 键盘快捷键
任何高级用户都知道,键盘快捷键将为您节省大量时间。Jupyter 在顶部菜单下存储了一个键盘快捷键列表:帮助 > 键盘快捷键,或者在命令模式下按 H(稍后会详细介绍)。每次更新 Jupyter 时都值得检查一下,因为一直在添加更多快捷方式。
访问键盘快捷键的另一种方法以及学习它们的便捷方法是使用命令面板:Cmd + Shift + P(或 Ctrl + Shift + P 在 Linux 和 Windows 上)。此对话框可帮助您按名称运行任何命令 - 如果您不知道操作的键盘快捷键或您想要执行的操作没有键盘快捷键,则此对话框非常有用。该功能类似于 Mac 上的 Spotlight 搜索,一旦您开始使用它,您会想知道没有它您会如何生活!
命令面板。
我最喜欢的一些:
- Esc 将带您进入命令模式,您可以在其中使用箭头键在笔记本中导航。
- 在命令模式下:A 在当前单元格上方插入一个新单元格,B 在下方插入一个新单元格。M 将当前单元格更改为 Markdown,Y 将其更改回 codeD + D(按两次键)删除当前单元格
- Enter 会将您从命令模式带回给定单元格的编辑模式。
- Shift + Tab 将向您显示您刚刚在代码单元格中键入的对象的 Docstring(文档)——您可以一直按这个快捷键来循环浏览几种文档模式。
- Ctrl + Shift + - 将从光标所在的位置将当前单元格分成两个。
- Esc + F 查找和替换您的代码,而不是输出。
- Esc + O 切换单元格输出。
- 选择多个单元格:Shift + J 或 Shift + Down 选择向下的下一个卖出。您还可以使用 Shift + K 或 Shift + Up 选择向上方向的销售。一旦选择了单元格,您就可以批量删除/复制/剪切/粘贴/运行它们。当您需要移动笔记本的某些部分时,这很有用。您还可以使用 Shift + M 来合并多个单元格。
合并多个单元格。
2. 漂亮的变量展示
第一部分是众所周知的。通过使用变量名称或语句的未分配输出完成 Jupyter 单元格,Jupyter 将显示该变量,而无需打印语句。这在处理 Pandas DataFrames 时特别有用,因为输出被整齐地格式化为表格。
鲜为人知的是,您可以更改 ast_note_interactivity 内核选项的修改,使 jupyter 对其自己行上的任何变量或语句执行此操作,因此您可以一次查看多个语句的值。
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from pydataset import data
quakes = data('quakes')
quakes.head()
quakes.tail()
latlongdepthmagstations1-20.42181.625624.8412-20.62181.036504.2153-26.00184.10425.4434-17.97181.666264.1195-20.9614
latlongdepthmagstations996-25.93179.544704.422997-12.28167.062484.735998-20.13184.202444.534999-17.40187.80404.5016161616161616174
如果要为 Jupyter 的所有实例(笔记本和控制台)设置此行为,只需使用以下行创建一个文件 ~/.ipython/profile_default/ipython_config.py。
c = get_config()
# Run all nodes interactively
c.InteractiveShell.ast_node_interactivity = "all"
3. 简单的文档链接
在“帮助”菜单中,您可以找到指向常用库(包括 NumPy、Pandas、SciPy 和 Matplotlib)的在线文档的便捷链接。
也不要忘记,通过在库、方法或变量前面加上 ?,您可以访问 Docstring 以快速参考语法。
?str.replace()
Docstring:
S.replace(old, new[, count]) -> str
Return 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 内联激活——这是一个 Dataquest Matplotlib 教程。
- %matplotlib notebook 提供交互性,但可能有点慢,因为渲染是在服务器端完成的。
- Seaborn 基于 Matplotlib 构建,可以更轻松地构建更具吸引力的图。只需导入 Seaborn,您的 matplotlib 图就会变得“更漂亮”,无需任何代码修改。
- mpld3 为 matplotlib 代码提供替代渲染器(使用 d3)。很不错,虽然不完整。
- 散景是构建交互式绘图的更好选择。
- plot.ly 可以生成漂亮的图——这曾经是一项付费服务?,但最近开源。
- Altair 是一个相对较新的 Python 声明式可视化库。它易于使用并且可以绘制出漂亮的图,但是自定义这些图的能力并不像 Matplotlib 中那样强大。
Jupyter 界面。
5. IPython 魔法命令
你在上面看到的 %matplotlib inline 是一个 IPython Magic 命令的例子。Jupyter 基于 IPython 内核,可以访问 IPython 内核中的所有魔法,它们可以让您的生活更轻松!
# 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 %xmode
Available 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 %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.
我建议您浏览所有 IPython Magic 命令的文档,因为您无疑会找到一些适合您的命令。以下是我最喜欢的一些:
6. IPython Magic – %env: 设置环境变量
您可以在不重新启动 jupyter 服务器进程的情况下管理笔记本的环境变量。一些库(如 theano)使用环境变量来控制行为,%env 是最方便的方式。
# Running %env without any arguments
# lists all environment variables
# The line below sets the environment
# variable
%env OMP_NUM_THREADS%env OMP_NUM_THREADS=4
env: OMP_NUM_THREADS=4
7. IPython Magic – %run: 执行python代码
%run 可以从 .py 文件执行 python 代码——这是有据可查的行为。鲜为人知的是,它也可以执行其他 jupyter notebook,这非常有用。
请注意,使用 %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.py
if __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 data
del data # This has deleted the variable
Stored 'data' (str)
现在,在一个新的笔记本中……
%store -r data
print(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 魔法——计时
有两个 IPython Magic 命令对计时很有用——%%time 和 %timeit。当您有一些缓慢的代码并且您试图确定问题所在时,这些特别方便。
%%time 将为您提供有关单元格中代码单次运行的信息。
%%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 次的平均值。
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 魔法将该单元格的内容保存到外部文件。%pycat 做相反的事情,并显示(在弹出窗口中)外部文件的语法突出显示内容。
%%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
%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)
### 13. IPython Magic – %prun:显示你的程序在每个函数中花费了多少时间。使用 `%prun statement_name` 会给你一个有序表,显示每个内部函数在语句中被调用的次数,每次调用花费的时间以及函数所有运行的累积时间。
%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}
14. IPython Magic – 用 %pdb 调试
Jupyter 有自己的 Python 调试器 (pdb) 接口。这使得进入函数内部并调查那里发生的事情成为可能。
您可以在此处查看 pdb 的可接受命令列表。
%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>
15. IPython Magic——Retina笔记本的高分辨率绘图输出
一行 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 inline
from matplotlib import pyplot as plt
import numpyx = numpy.linspace(0, 1, 1000)**1.5
# Here you get the output of the function
plt.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 命令
从笔记本内部执行 shell 命令很容易。您可以使用它来检查工作文件夹中可用的数据集:
!ls *.csv
nba_2016.csv titanic.csv
pixar_movies.csv whitehouse_employees.csv
或者检查和管理包。
!pip install numpy
!pip list | grep pandas
Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages
pandas (0.18.1)
18. 在论坛中使用 LaTeX
当您在 Markdown 单元格中编写 LaTeX 时,它将使用 MathJax 呈现为公式。
这:
$P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)}$
变成这样:
P(A∣B)=P(B∣A)P(A)P(B)
Markdown 是 notebooks 的重要组成部分,所以不要忘记使用它的表现力!
19. 在笔记本中运行不同内核的代码
如果需要,您可以将来自多个内核的代码合并到一个笔记本中。
只需在要使用该内核的每个单元格的开头使用带有内核名称的 IPython Magics:
- %%bash
- %%HTML
- %%蟒蛇2
- %%蟒蛇3
- %%红宝石
- %%perl
%%bash
for i in {1..5}
do
echo "i is $i"
done
i is 1
i is 2
i is 3
i is 4
i is 5
20. 为 Jupyter 安装其他内核
Jupyter 的一个很好的特性是能够运行不同语言的内核。例如,这里是如何运行 R 内核。
简单选项:使用 Anaconda 安装 R 内核
如果您使用 Anaconda 来设置您的环境,那么让 R 工作非常容易。只需在终端中运行以下命令:
conda install -c r r-essentials
不太简单的选项:手动安装 R 内核
如果您不使用 Anaconda,则该过程会稍微复杂一些。首先,如果您还没有安装 R,则需要从 CRAN 安装 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 轻松完成:
pip install rpy2
然后您可以一起使用这两种语言,甚至可以在两者之间传递变量:
%load_ext rpy2.ipython
%R require(ggplot2)
array([1], dtype=int32)
import pandas as pd
df = 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 df
ggplot(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
%%cython
def myltiply_by_2(float x):
return 2.0 * x
myltiply_by_2(23.)
我个人更喜欢使用 fortran,我发现它对于编写数字运算函数非常方便。可以在此处找到更多使用细节。
%load_ext fortranmagic
%%fortran
subroutine compute_fortran(x, y, z)
real, intent(in) :: x(:), y(:)
real, intent(out) :: z(size(x, 1))
z = sin(x + y)
end subroutine compute_fortran
compute_fortran([1, 2, 3], [4, 5, 6])
还有不同的抖动系统可以加速你的 python 代码。可以在此处找到更多示例。
23. 多光标支持
Jupyter 支持多个游标,类似于 Sublime Text。只需在按住 Alt 的同时单击并拖动鼠标。
多光标支持。
24. Jupyter-contrib 扩展
Jupyter-contrib 扩展是一个扩展系列,它为 Jupyter 提供了更多功能,包括例如 jupyter 拼写检查器和代码格式化器。
以下命令将安装扩展,以及一个基于菜单的配置器,可帮助您从 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
nbextension 配置器。
25. 从 Jupyter 笔记本创建演示文稿。
Damian Avila 的 RISE 允许您从现有笔记本创建 PowerPoint 风格的演示文稿。
您可以使用 conda 安装 RISE:
conda install -c damianavila82 rise
或者 pip:
pip install RISE
然后运行以下代码来安装和启用扩展:
jupyter-nbextension install rise --py --sys-prefix
jupyter-nbextension enable rise --py --sys-prefix
26. Jupyter 输出系统
笔记本显示为 HTML,单元格输出可以是 HTML,因此您几乎可以返回任何内容:视频/音频/图像。
在本例中,我扫描了存储库中带有图像的文件夹,并显示前 5 个的缩略图:
import os
from IPython.display import display, Image
names = [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))
names = !ls ../images/ml_demonstrations/*.png
names[:5]
names = !ls ../images/ml_demonstrations/*.png
names[: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 操作的不错选择。我们在 rep 中使用它来并行训练许多机器学习模型
- 火花
- spark-sql 魔法 %%sql
28. 共享笔记本
共享 notebook 的最简单方法是使用 notebook 文件 (.ipynb),但对于那些不使用 Jupyter 的人,您有几个选择:
- 使用文件 > 下载为 > HTML 菜单选项将笔记本转换为 html 文件。
- 与 gists 或在 github 上共享您的笔记本文件,这两者都呈现笔记本。请参阅此示例。如果您将笔记本上传到 github 存储库,则可以使用方便的 mybinder 服务允许某人半小时的交互式 Jupyter 访问您的存储库。
- 使用 jupyterhub 设置您自己的系统,当您组织迷你课程或研讨会并且没有时间关心学生机器时,这非常方便。
- 将您的笔记本存放在保管箱中,然后将链接放入 nbviewer。nbviewer 将从您托管它的任何来源呈现笔记本。
- 使用文件 > 下载为 > PDF 菜单将您的笔记本另存为 PDF。如果您要走这条路,我强烈建议您阅读 Julius Schulz 的优秀文章使出版准备好 Python 笔记本。
- 使用 Pelican 从您的 Jupyter 笔记本创建博客。