大数据文摘
Jupyter Notebook 的 27 个窍门,技巧和快捷键 大数据文摘作品,转载具体要求见文末翻译 | 姜范波
校对 | 毛丽 & 寒小阳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 + 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 ] :
mag stations
562 4.8 41
650 4.2 15
626 4.1 19
649 4.0 11
996 -25.93
470 4.4 22
997 -12.28
248 4.7 35
998 -20.13
244 4.5 34
999 -17.40
165 6.0 119如果你想在各种情形下(Notebook 和 Console)Jupyter 都同样处理,用下面的几行简单的命令创建文件 ~/.ipython/profile_default/ipython_config.py 即可实现:c = get_config ( ) # Run all nodes interactivelyc.InteractiveShell.ast_node_interactivity = "all"3. 轻松链接到文档在 Help
菜单下,你可以找到常见库的在线文档链接,包括 Numpy,Pandas,Scipy 和 Matplotlib 等。 另外,在库、方法或变量的前面打上 ?,即可打开相关语法的帮助文档。In
[ 3 ] : ?str.replace ( )
Docstring:
S.replace ( old, new [ , count ]
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.
method_descriptor4. 在 notebok 里作图在 notebook 里作图,有多个选择: -
(事实标准)(http://matplotlib.org/),可通过 %matplotlib inline 激活, - %matplotlib notebook
提供交互性操作,但可能会有点慢,因为响应是在服务器端完成的。 -
提供 matplotlib 代码的替代性呈现(通过 d3),虽然不完整,但很好。 -
生成可交互图像的更好选择。 -
可以生成非常好的图,可惜是付费服务。 5.Jupyter Magic 命令上文提到的 %matplotlib inline
是 Jupyter Magic 命令之一。 推荐阅读,它一定会对你很有帮助。下面是我最爱的几个:6.Jupyter Magic-%env: 设置环境变量不必重启 jupyter 服务器进程,也可以管理 notebook 的环境变量。有的库(比如 theano)使用环境变量来控制其行为,%env 是最方便的途径。In
# 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=47.Jupyter Magic-%run: 运行 python 代码%run 可以运行 .py 格式的 python 代码——这是众所周知的。不那么为人知晓的事实是它也可以运行其它的 jupyter notebook 文件,这一点很有用。 注意:使用 %run 与导入一个 python 模块是不同的。In
# this will execute and show the output from
# all code cells of the specified notebook
%run ./two-histograms.ipynb 8.Jupyter Magic-%load:从外部脚本中插入代码该操作用外部脚本替换当前 cell。可以使用你的电脑中的一个文件作为来源,也可以使用 URL。In
# Before Running
%load ./hello_world.pyIn
# After Running
# %load ./hello_world.py
if __name__ == "__main__":
print ( "Hello World!" )
Hello World!9.Jupyter Magic-%store:在 notebook 文件之间传递变量%store
命令可以在两个 notebook 文件之间传递变量。In
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 notebook10.Jupyter Magic-%who:列出所有的全局变量不加任何参数,
命令可以列出所有的全局变量。加上参数
将只列出字符串型的全局变量。In
[ 1 ] : one = "for the money"
two = "for the show"
three = "to get ready now go cat go"
11.Jupyter Magic- 计时有两种用于计时的 jupyter magic 命令:
%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 u s per loop12.Jupyter Magic-writefile and %pycat: 导出 cell 内容 / 显示外部脚本的内容使用 %%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.pyIn
[ 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 ) 13.Jupyter Magic-%prun:告诉你程序中每个函数消耗的时间使用 %prun+ 函数声明会给你一个按顺序排列的表格,显示每个内部函数的耗时情况,每次调用函数的耗时情况,以及累计耗时。In
%prun some_useless_slow_function ( )
26324 function calls in 0.556 seconds
Ordered by: internal time
percall filename:lineno ( function )
0.000 &ipython-input-46-bd5&:2 ( append_if_not_exists )
0.000 {method 'randint' of 'mtrand.RandomState' objects}
0.556 &ipython-input-46-bd5&:6 ( some_useless_slow_function )
0.000 {method 'append' of 'list' objects}
0.556 &string&:1 ( &module& )
0.556 {built-in method exec}
0.000 {method 'disable' of '_lsprof.Profiler' objects}14.Jupyter Magic- 用 %pdb 调试程序Jupyter 有自己的调试界面,使得进入函数内部检查错误成为可能。 Pdb 中可使用的命令见In
def pick_and_take ( ) :
picked = numpy.random.randint ( 0, 1000 )
raise NotImplementedError ( )
pick_and_take ( )
Automatic pdb calling has been turned ON
---------------------------------------------------------------------------
NotImplementedError
( most recent call last )
&ipython-input-24-0f6b26649b2e& in &module& ( )
raise NotImplementedError ( )
----& 7 pick_and_take ( )
&ipython-input-24-0f6b26649b2e& in pick_and_take ( )
3 def pick_and_take ( ) :
picked = numpy.random.randint ( 0, 1000 )
raise NotImplementedError ( )
7 pick_and_take ( )
NotImplementedError:
& &ipython-input-24-0f6b26649b2e& ( 5 ) pick_and_take ( )
3 def pick_and_take ( ) :
picked = numpy.random.randint ( 0, 1000 )
raise NotImplementedError ( )
7 pick_and_take ( )
ipdb&15. 末句函数不输出有时候不让末句的函数输出结果比较方便,比如在作图的时候,此时,只需在该函数末尾加上一个分号即可。In
[ 4 ] : %matplotlib inline
from matplotlib import pyplot as plt
import numpy
x = numpy.linspace ( 0, 1, 1000 ) **1.5In
[ 5 ] : # Here you get the output of the function
plt.hist ( x ) Out [ 5 ] :
&a list of 10 Patch objects& ) In
[ 6 ] : # By adding a semicolon at the end, the output is suppressed.
plt.hist ( x ) ;16. 运行 Shell 命令在 notebook 内部运行 shell 命令很简单,这样你就可以看到你的工作文件夹里有哪些数据集。In
[ 7 ] : !ls *.csvnba_2016.csv
titanic.csvpixar_movies.csv
whitehouse_employees.csv17. 用 LaTex 写公式当你在一个 Markdown 单元格里写 LaTex 时,它将用 MathJax 呈现公式:如
P ( A mid B )
= frac{P ( B mid A )
, P ( A ) }{P ( B ) } $$会变成
18. 在 notebook 内用不同的内核运行代码如果你想要,其实可以把不同内核的代码结合到一个 notebook 里运行。 只需在每个单元格的起始,用 Jupyter magics 调用 kernal 的名称:%%bash%%HTML%%python2%%python3%%ruby%%perlIn
[ 6 ] : %%bash
for i in {1..5}
echo "i is $i"
i is 519. 给 Jupyter 安装其他的内核Jupyter 的优良性能之一是可以运行不同语言的内核。下面以运行 R 内核为例说明:简单的方法:通过 Anaconda 安装 R 内核conda install -c r r-essentials稍微麻烦的方法:手动安装 R 内核如果你不是用 Anaconda,过程会有点复杂,首先,你需要从 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 installation20. 在同一个 notebook 里运行 R 和 Python要这么做,最好的方法事安装 rpy2(需要一个可以工作的 R),用 pip 操作很简单: pip install rpy2
然后,就可以同时使用两种语言了,甚至变量也可以在二者之间公用:In
[ 1 ] : %load_ext rpy2.ipythonIn
[ 2 ] : %R require ( ggplot2 ) Out [ 2 ] : array (
[ 1 ] , dtype=int32 ) In
[ 3 ] : import pandas as pd
df = pd.DataFrame ( {
[ 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c' ] ,
[ 4, 3, 5, 2, 1, 7, 7, 5, 9 ] ,
[ 0, 4, 3, 6, 7, 10, 11, 9, 13 ] ,
[ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
[ 4 ] : %%R -i df
ggplot ( data = df )
+ geom_point ( aes ( x = X, y= Y, color = Letter, size = Z ) )
21. 用其他语言写函数有时候 numpy 的速度有点慢,我想写一些更快的代码。 原则上,你可以在动态库里编译函数,用 python 来封装…
但是如果这个无聊的过程不用自己干,岂不更好?你可以在 cython 或 fortran 里写函数,然后在 python 代码里直接调用。 首先,你要先安装:!pip install cython fortran-magic In
] : %load_ext CythonIn
] : %%cython
def myltiply_by_2 ( float x ) :
return 2.0 * xIn
] : myltiply_by_2 ( 23. ) 我个人比较喜欢用 Fortran,它在写数值计算函数时十分方便。更多的细节在。In
] : %load_ext fortranmagicIn
] : %%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_fortranIn
] : compute_fortran (
[ 1, 2, 3 ] ,
[ 4, 5, 6 ]
) 还有一些别的跳转系统可以加速 python 代码。更多的例子见(http://arogozhnikov.github.io//SpeedBenchmarks.html)你可以在 cython 或 fortran 里写函数,然后在 python 代22. 支持多指针Jupyter 支持多个指针同步编辑,类似 Sublime Text 编辑器。按下 Alt 键并拖拽鼠标即可实现。 23.Jupyter 外界拓展是一些给予 Jupyter 更多更能的延伸程序,包括 jupyter spell-checker 和 code-formatter 之类 .
下面的命令安装这些延伸程序,同时也安装一个菜单形式的配置器,可以从 Jupyter 的主屏幕浏览和激活延伸程序。!pip install /ipython-contrib/jupyter_contrib_nbextensions/tarball/master!pip install jupyter_nbextensions_configurator!jupyter contrib nbextension install --user!jupyter nbextensions_configurator enable --user24. 从 Jupyter notebook 创建演示稿Damian Avila 的允许你从已有的 notebook 创建一个 powerpoint 形式的演示稿。 你可以用 conda 来安装 RISE:conda install -c damianavila82 rise或者用 pip 安装:pip install RISE然后运行下面的代码来安装和激活延伸程序:jupyter-nbextension install rise --py --sys-prefixjupyter-nbextension enable rise --py --sys-prefix25.Jupyter 输出系统Notebook 本身以 HTML 的形式显示,单元格输出也可以是 HTML 形式的,所以你可以输出任何东西:视频 / 音频 / 图像。 这个例子是浏览我所有的图片,并显示前五张图的缩略图。In
from IPython.display import display, Image
[ 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 命令创建一个相同的列表,因为 magics 和 bash 运行函数后返回的是 python 变量:In
names = !ls ../images/ml_demonstrations/*.png
names [ :5 ] Out [ 10 ] :
[ '../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' ] 26. 大数据分析很多方案可以解决查询 / 处理大数据的问题:27. 分享 notebook分享 notebook 最方便的方法是使用 notebook 文件(.ipynb),但是对那些不使用 notebook 的人,你还有这些选择:在评论里告诉我哪些是你的最爱小窍门吧!原文链接:https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/关于转载如需转载,请在开篇显著位置注明作者和出处(转自:大数据文摘 |bigdatadigest),并在文章结尾放置大数据文摘醒目二维码。无原创标识文章请按照转载要求编辑,可直接转载,转载后请将转载链接发送给我们;有原创标识文章,请发送【文章名称 - 待授权公众号名称及 ID】给我们申请白名单授权。未经许可的转载以及改编者,我们将依法追究其法律责任。联系邮箱:。大数据文摘后台回复 " 志愿者 ",了解如何加入我们面向软件工程师的机器学习每日学习计划 | 附大量资料
相关标签:
原网页已经由 ZAKER 转码排版
互联网新闻3小时前
互联网新闻18小时前
互联网新闻21小时前
36氪1小时前
ZD至顶网1小时前
亿欧网53分钟前
36氪2小时前
36氪3小时前
人人都是产品经理1小时前
36氪1小时前
品途网2小时前
人人都是产品经理2小时前
36氪2小时前
人人都是产品经理3小时前
亿欧网3小时前页面已拦截
无锡网警提示您:
该网站已被大量用户举报,存在以游戏充值的名义盗取银行或游戏帐号的嫌疑。问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
如题在终端上启动jupyter notebook时报404错误,窗口是打开了,但是没法用
错误信息如下:
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
git clone /ipython/ipython-components.git
把bootstrap/fonts/glyphicons-halflings-regular.eot拷贝进你的ipython
/usr/local/lib/python2.7/site-packages/IPython/html/static/components/bootstrap/fonts/
如果没有 fonts 文件夹就创建一个
不行就试试 anaconda 吧....
分享到微博?
你好!看起来你挺喜欢这个内容,但是你还没有注册帐号。 当你创建了帐号,我们能准确地追踪你关注的问题,在有新答案或内容的时候收到网页和邮件通知。还能直接向作者咨询更多细节。如果上面的内容有帮助,记得点赞 (????)? 表示感谢。
明天提醒我
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:这几天学习jupyter notebook,用pip安装的jupyter。但是命令行执行&jupyter nootbook&后提示没找到zmq.libzmq。怒啊~~!!!
baidu+google了一番,有2种解决方案:
1.pip安装pyzmq
2.github下载libzmq源码,然后编译。
第一种方法:试过之后发现然并卵。
第二种方法:首先我电脑上没有vs(好尴尬);其次安装libzmq过程中可能会发现缺少其他库(libsodium),需要下载源码编译(同学们,这简直就是递归啊!)。想尝试这种方法的同学请参考这篇文章
最后找到一种方法(抱歉 忘记怎么找到的了):
Microsoft官网下载vcforpython27.msi,双击安装。命令行试一下import zmq,啊? 啊!竟然没报错。又试一下jupyter notebook,啊? 啊!竟然成功启动!
vcforpython27是啥呢?
This package contains the compiler and set of system headers necessary for producing binary wheels for Python 2.7 packages.
我用的是python3.5,安装vcforpython27后同样能解决问题。
是不是用linux就不会遇到这些问题了呢?
阅读(...) 评论()