通过使用Jupyter Notebook,总结了25条心得体会。内容太多,分2期给大家分享一下。
1.键盘快捷键
任何高级用户都知道,键盘快捷键将为你节省大量时间。Jupyter在以下菜单的顶部菜单下存储了键盘快捷列表: Help > Keyboard Shortcuts或通过H 在命令模式下按 (稍后会详细介绍)。每次更新Jupyter时都值得查看一下,因为会添加更多快捷方式。
访问键盘快捷方式的另一种方法,是使用命令面板:( Cmd + Shift + P 或 Ctrl + Shift + P 在Linux和Windows上)。此对话框可按名称运行任何命令-如果不知道某个操作的键盘快捷键或要执行的操作没有键盘快捷键,则此对话框很有用。该功能类似于Mac上的Spotlight搜索。
命令面板
常用快捷键:
- Esc 将带你进入命令模式,可以使用箭头键在笔记本中浏览。
- 在命令模式下:
A 在当前单元格上方插入一个新单元格, B 在其下方插入一个新单元格。 M 将当前单元格更改为Markdown, Y 将其更改回代码 D + D (按两次键)删除当前单元格
- Enter 从命令模式返回到给定单元格的编辑模式。
- Shift + Tab 显示刚刚在代码单元中键入的对象的文档字符串(文档),可以继续按此快捷键以循环浏览几种文档模式。
- Ctrl + Shift + - 从光标所在的位置将当前单元格拆分为两个。
- Esc + F 查找并替换代码,而不替换输出。
- Esc + O 切换单元格输出。
- 选择多个单元格:
Shift + J 或 Shift + Down 选择向下的下一个。您也可以使用Shift + K 或 Shift + Up选择向上 。 选定单元格后,即可批量删除/复制/剪切/粘贴/运行它们。当需要移动笔记本计算机的部件时,这很有用。 也可以使用 Shift + M 合并多个单元格。
合并多个单元格
2.整齐的变量显示
第一部分是众所周知的。通过用变量名或语句的未分配输出完成Jupyter单元格,Jupyter将显示该变量。这在处理Pandas DataFrame时特别有用,因为输出被整齐地格式化为表格。
还可以更改
ast_note_interactivityModify kernel选项,以使Jupyter对任何变量或语句执行此操作,因此可以一次查看多个语句的值。
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from pydataset import data
quakes = data('quakes')
quakes.head()
quakes.tail()
如果要为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)在线文档的便捷链接。
同样不要忘记,通过在库,方法或变量添加之前,可以访问Docstring以快速获取语法参考。
?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.在笔记本中绘图
笔记本编辑图的小功能:
- %matplotlib notebook:提供交互性,但可能会有点慢,因为渲染是在服务器端完成的。
- Seaborn:建立在Matplotlib之上。只需导入Seaborn,您的matplotlib图就可以变得“更漂亮”,而无需进行任何代码修改。
- mpld3:为matplotlib代码提供了替代渲染器(使用d3)。
- 背景虚化
- plot.ly:可以生成漂亮的图,这曾经是一项付费服务,最近才开源。
- Altair:是一个相对较新的Python声明式可视化库。它易于使用且可制作精美的图,但是自定义这些图的功能却不如Matplotlib强大。
Jupyter界面
5. IPython魔术命令
基于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 %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.
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笔记本,这一点非常有用。
请注意,using %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不带任何参数的命令将列出全局范围中存在的所有变量。
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 将为您提供有关单元格中单次运行代码的信息。
%%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次(默认情况下),然后提供最快的三次平均值。
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 us 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}