Jupyter Notebook是一个基于Web的交互式工具,数据科学领域正在频繁的使用它。
在上篇文章中,我们介绍了如何安装使用Jupyter Notebook来快快乐乐的编程,以及一些快捷键sao操作、如何搭建一个开放的notebook让大家一起使用,最后我们介绍了怎样修改Jupyter Notebook的风格,让它更酷炫。
还没学过的同学快戳:Jupyter Notebook介绍(上篇)
补完课再回来啊!!!
通过上篇的介绍,相信大家已经可以自如的使用Jupyter了,今天我们继续介绍一下Jupyter Notebook的一些更酷的扩展功能。
魔术命令是ipython中的特殊命令,常以%
作为前缀符号开头,用于方便我们的日常使用。
%
:行魔法函数,只对本行代码生效。%%
:Cell魔法函数,在整个Cell中生效,必须放于Cell首行。
下面我们来介绍一下常用的magics。(完整的magics命令:大家可以打开jupyter后可以在cell中输入%quickref
显示快速参考卡,%lsmagic
:列出所有的魔法函数,以及%magic
命令可以显示魔术命令的详细文档)
%matplotlib inline
: 这个命令可能是大家最常用的一个魔术命令。这个命令用于将matplotlib的输出图嵌入到notebook中,如果不加这条命令,在用matplotlib绘图时可能会出现不显示的情况,举个我们在介绍seaborn中的例子:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
sns.set()
x = np.linspace(0,20,8)
y_bar = np.random.randint(5,20,8)
y_line = y_bar
plt.figure(figsize=(8,6))
plt.bar(x, y_bar, color='r')
plt.plot(x, y_line, '-o', color='g')
plt.tick_params(labelsize='15', width=1)
plt.show()
%time, %timeit和 %%time, %%timeit
:可以用来记录程序运行的时间,以便于后期对代码逻辑进行优化。%time
可以输出单个语句的运行时间,而%timeit
会自动多次执行语句以产生一个更具代表性的平均执行时间, %%time
可以输出整个cell中语句的执行时间。
import time
import numpy as np
def time_test():
arr = np.random.rand(5,6)
for i in range(10000):
arr += (-1)**i
return arr
%time time_test()
# OUTPUT:
"""
CPU times: user 26 ms, sys: 2.16 ms, total: 28.2 ms
Wall time: 27 ms
array([[0.9002168 , 0.3041222 , 0.44203939, 0.17079689, 0.94881637,
0.3497185 ],
[0.3253366 , 0.94237406, 0.94394366, 0.45562757, 0.13917467,
0.34043364],
[0.17794278, 0.51184239, 0.30619056, 0.17429579, 0.92800944,
0.4405044 ],
[0.30972439, 0.02095686, 0.31532945, 0.65237745, 0.03647221,
0.54834167],
[0.9697625 , 0.52372474, 0.12283473, 0.46851531, 0.09019544,
0.41063005]])
"""
%timeit time_test()
# OUTPUT:
"""
17.1 ms ± 187 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
"""
%%time
import time
import numpy as np
def time_test():
arr = np.random.rand(5,6)
for i in range(10000):
arr += (-1)**i
return arr
time_test()
# OUTPUT:
"""
CPU times: user 24.5 ms, sys: 914 µs, total: 25.4 ms
Wall time: 25 ms
"""
%xdel
:删除一个变量,清除相关的引用。%prun, %lprun, %memit, %mprun
:程序性能分析。注:后面三个magics命令不是jupyter自带的,需要先进行安装和导入才可以使用。
$ pip install line_profiler
%load_ext line_profiler
$ pip install memory_profiler
%load_ext memory_profiler
%load_ext
:导入ipython的拓展工具。Load an IPython extension by its module name.
%run
:运行python脚本:%run script.py
%system date, !date 和 !!date
: 都可用于在cell中执行shell命令。%who_ls, %who, %whos
:输出环境中的变量列表。%who_ls function
仅仅输入函数类型的变量列表。
%whos
#OUTPUT
"""
Variable Type Data/Info
---------------------------------
np module <module 'numpy' from '/Us<...>kages/numpy/__init__.py'>
time module <module 'time' (built-in)>
time_test function <function time_test at 0x10f433620>
"""
%debug, %pdb
:可用于调试debug%env
:列出全部环境变量%reset
:清除全部变量%%
: Cell magics:在每个cell的开头使用的以%%
开头的魔法命令,可以在一个notebook中用不同的内核运行代码,例如:%%bash
%%markdown
%%time
%%HTML
%%python2
%%python3
%%latex
%%javascript
%%ruby
%%perl
安装方法:
!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
安装完成后打开jupyter可以看到多了Nbextensions这个选项卡:
安装了之后便多了很多便捷的小工具可以选择,可以直接在上图显示的Nbextensions这个选项卡中直接打开相应的功能。下面介绍一些常见的:
更多的扩展功能大家可以自行探索啊。
?
,??
:可以在jupyter中实现help的功能。np.random.rand??
# OUTPUT:
"""
Docstring:
rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and populate it with
random samples from a uniform distribution
over ``[0, 1)``.
Parameters
----------
d0, d1, ..., dn : int, optional
The dimensions of the returned array, should all be positive.
If no argument is given a single Python float is returned.
Returns
-------
out : ndarray, shape ``(d0, d1, ..., dn)``
Random values.
See Also
--------
random
Notes
-----
This is a convenience function. If you want an interface that
takes a shape-tuple as the first argument, refer to
np.random.random_sample .
Examples
--------
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
Type: builtin_function_or_method
"""