【精心解讀】關於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 InteractiveShellnInteractiveShell.ast_node_interactivity = "all" nfrom pydataset import datanquakes = data(quakes)nquakes.head()nquakes.tail() n

如果要為Jupyter(Notebook和Console)的所有實例設置此行為,只需使用下面的行創建?/ .ipython / profile_default / ipython_config.py文件即可。

c = get_config()nn# Run all nodes interactivelync.InteractiveShell.ast_node_interactivity = "all"n

3、易於鏈接到文檔

在「幫助」菜單中,您可以找到包含NumPy,Pandas,SciPy和Matplotlib等通用庫的在線文檔的便捷鏈接。

另外不要忘記,通過在庫中添加庫,方法或變數。

?str.replace()n

Docstring:nS.replace(old, new[, count]) -> strnnReturn a copy of S with all occurrences of substringnold replaced by new. If the optional argument count isngiven, only the first count occurrences are replaced.nType: method_descriptorn

4、繪圖

  • matplotlib,用%matplotlib inline激活 。(matplotlib.org/)
  • %matplotlib提供交互性,但可能有點慢,因為渲染是在伺服器端完成的。
  • Seaborn建立在Matplotlib之上, 只需通過導入Seaborn,你的matplotlib就會變得更漂亮,不需要修改任何代碼。(seaborn.pydata.org/)
  • mpld3為matplotlib代碼提供了替代渲染器(使用d3)。 相當不錯,雖然不完整。(github.com/mpld3/mpld3)
  • bokeh是建立互動式更好選擇。(bokeh.pydata.org/en/lat)
  • plot.ly可以提供更好的plots - 這曾經只是一個付費服務,但最近是開源le 。(plot.ly/)
  • Altair是一個相對較新的用Python的可視化庫。 使用起來非常簡單,並且可以製作出非常好看的圖,但是定製這些圖的能力並不像Matplotlib那樣強大。(github.com/altair-viz/a)

5、IPython Magic命令

上面看到的%matplotlib是一個IPython Magic命令的例子。 基於IPython內核,Jupyter可以從IPython內核訪問所有的Magics,它可以讓你的工作變得更容易!

# This will list all magic commandsn%lsmagicn

Available line magics:n%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 %xmodennAvailable cell magics:n%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefilennAutomagic is ON, % prefix IS NOT needed for line magics.n

建議瀏覽所有IPython Magic命令的文檔,因為你會發現一些適合你的工具。(ipython.readthedocs.io/)

6、IPython Magic - %env:設置環境變數

你可以管理Jupyter的環境變數,而無需重新啟動Jupyter伺服器進程。 有些庫(如theano)使用環境變數來控制行為,%env是最方便的方法。

# Running %env without any argumentsn# lists all environment variablesnn# The line below sets the environmentn# variable OMP_NUM_THREADSn%env OMP_NUM_THREADS=4n

env: OMP_NUM_THREADS=4n

7、IPython Magic - %run:執行python代碼

%run可以從.py文件中執行python代碼,鮮為人知的是,它也可以執行其他jupyter notebooks,相當有用。

請注意,使用%run與導入python模塊不同。

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

8、IPython Magic - %load:從外部腳本插入代碼

這將用外部腳本替換單元格的內容。 你可以使用計算機上的文件作為源,也可以使用URL。

# Before Runningn%load ./hello_world n

# After Runningn# %load ./hello_world.pynif __name__ == "__main__":n print("Hello World!")n

Hello World!n

9、IPython Magic - %store:在筆記本之間傳遞變數

%store命令可以讓你在兩個不同的文件之間傳遞變數。

data = this is the string I want to pass to different notebookn%store datandel data # This has deleted the variablen

Stored data (str) n

new

%store -r datanprint(data) n

this is the string I want to pass to different notebook n

10、IPython Magic - %who:列出全局範圍的所有變數

沒有任何參數的%who命令將列出全局範圍中存在的所有變數。 傳遞像str這樣的參數將僅列出該類型的變數。

one = "for the money"ntwo = "for the show"nthree = "to get ready now go cat go" n%who strn

one three two n

11、IPython Magic - 時間

有兩個IPython Magic命令對時間有效 - %%time和%timeit。

%%time會給你關於單元中的代碼的單一運行的信息。

%%timenimport timenfor _ in range(1000):n time.sleep(0.01)# sleep for 0.01 secondsn

CPU times: user 21.5 ms, sys: 14.8 ms, total: 36.3 msnWall time: 11.6 sn

import numpyn%timeit numpy.random.normal(size=100) n

The slowest run took 7.29 times longer than the fastest. This could mean that an intermediate result is being cached.n100000 loops, best of 3: 5.5 μs per loop n

12、IPython Magic - %% writefile和%pycat:導出單元格的內容/顯示外部腳本的內容

使用%% writefile magic將該單元格的內容保存到外部文件中。 %pycat會做相反的處理,並顯示(在彈出窗口中)外部文件高亮內容。

%%writefile pythoncode.pynnimport numpyndef append_if_not_exists(arr, x):n if x not in arr:n arr.append(x)nndef some_useless_slow_function():n arr = list()n for i in range(10000):n x = numpy.random.randint(0, 10000)n append_if_not_exists(arr, x)n

Writing pythoncode.pynn%pycat pythoncode.pynn```pythonnimport numpyndef append_if_not_exists(arr, x):n if x not in arr:n arr.append(x)nndef some_useless_slow_function():n arr = list()n for i in range(10000):n x = numpy.random.randint(0, 10000)n append_if_not_exists(arr, x)nn### 13. IPython Magic - %prun: Show how much time your program spent in each function.nnUsing `%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.nnn```pythonn%prun some_useless_slow_function()nn26324 function calls in 0.556 secondsnnOrdered by: internal timennncalls tottime percall cumtime percall filename:lineno(function)n10000 0.527 0.000 0.528 0.000 <ipython-input-46-b52343f1a2d5>:2(append_if_not_exists)n10000 0.022 0.000 0.022 0.000 {method randint of mtrand.RandomState objects}n 1 0.006 0.006 0.556 0.556 <ipython-input-46-b52343f1a2d5>:6(some_useless_slow_function)n 6320 0.001 0.000 0.001 0.000 {method append of list objects}n 1 0.000 0.000 0.556 0.556 <string>:1(<module>)n 1 0.000 0.000 0.556 0.556 {built-in method exec}n 1 0.000 0.000 0.000 0.000 {method disable of _lsprof.Profiler objects}n

14.、IPython Magic - 用%pdb進行調試

Jupyter擁有自己的Python Debugger(pdb)介面。 這使得調試成為可能。

你可以在這裡查看a list of accepted commands for pdb here.(docs.python.org/3.5/lib)

%pdbnndef pick_and_take():n picked = numpy.random.randint(0, 1000)n raise NotImplementedError()nnpick_and_take()nnAutomatic pdb calling has been turned ONn

---------------------------------------------------------------------------nNotImplementedError Traceback (most recent call last)n<ipython-input-24-0f6b26649b2e> in <module>()n 5 raise NotImplementedError()n 6 n----> 7 pick_and_take()nn<ipython-input-24-0f6b26649b2e> in pick_and_take()n 3 def pick_and_take():n 4 picked = numpy.random.randint(0, 1000)n----> 5 raise NotImplementedError()n 6 n 7 pick_and_take()nnNotImplementedError:n

> <ipython-input-24-0f6b26649b2e>(5)pick_and_take()n 3 def pick_and_take():n 4 picked = numpy.random.randint(0, 1000)n----> 5 raise NotImplementedError()n 6 n 7 pick_and_take()n

ipdb>n

15、IPython Magic - 輸出Retina notebooks的高解析度繪圖

一行神奇的IPython會給你的Retina屏幕輸出雙解析度繪圖像,比如Macbook。 注意:下面的例子不會在非視網膜屏幕上渲染。

x = range(1000)ny = [i ** 2 for i in x]nplt.plot(x,y)nplt.show();nn%config InlineBackend.figure_format = retinanplt.plot(x,y)nplt.show(); n

16、阻止最終函數的輸出

有時候在最後一行阻止函數的輸出是很方便的,例如繪圖時。 要做到這一點,你只需在最後添加一個分號。

%matplotlib inlinenfrom matplotlib import pyplot as pltnimport numpynx = numpy.linspace(0, 1, 1000)**1.5n# Here you get the output of the functionnplt.hist(x)n(array([ 216., 126., 106., 95., 87., 81., 77., 73., 71., 68.]),narray([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),n<a list of 10 Patch objects>)n# By adding a semicolon at the end, the output is suppressed.nplt.hist(x); n

17、執行Shell命令

從 notebook內部執行shell命令很容易。 你可以使用它來檢查工作文件夾中可用的數據集:

!ls *.csvnnba_2016.csv titanic.csvnpixar_movies.csv whitehouse_employees.csvn

!pip install numpyn!pip list | grep pandasnRequirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packagesnpandas (0.18.1)n

18、使用LaTeX的公式

當你在Markdown單元格中編寫LaTeX時,使用MathJax將其渲染為公式。

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

19、運行代碼從其他內核在notebook中

如果你喜歡,你可以將來自多個內核的代碼組合到一個notebook中。

只需在每個單元的開始處使用IPython Magics以及你的內核的名稱就可以使用該內核:

  • %%bash
  • %%HTML
  • %%python2
  • %%python3
  • %%ruby
  • %%perl

%%bashnfor i in {1..5}ndon echo "i is $i"ndoneni is 1ni is 2ni is 3ni is 4ni is 5n

20、安裝Jupyter的其他內核

Jupyter的一個很好的功能是能夠運行不同語言的內核。 舉個例子,這裡是如何獲取R內核運行。

簡單選項:使用Anaconda安裝R內核

如果你使用Anaconda來設置你的環境,那麼讓R工作非常容易。 在終端上運行下面的代碼:

conda install -c r r-essentials n

較不容易的選項:手動安裝R內核

如果你不使用Anaconda,這個過程會更複雜一些。 首先,如果您尚未安裝R,則需要安裝R。

完成之後,啟動R控制台並運行以下命令:

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

21、在同一個 notebook中運行R和Python

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

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

22、用其他語言編寫函數

有時numpy的速度是不夠的,我們需要寫一些速度較快的代碼。

原則上,你可以在動態庫中編譯函數並編寫Python包裝器...

但是,這個無聊的部分應該你做嗎?

你可以用cython或者fortran編寫函數,直接從python代碼中使用。

首先你需要安裝:

!pip install cython fortran-magic nn%load_ext Cythonnn%%cythonndef myltiply_by_2(float x):n return 2.0 * xn nmyltiply_by_2(23.)n

個人更喜歡使用fortran,這對於編寫數字運算函數非常方便。 更多的使用細節可以在這裡找到。(arogozhnikov.github.io/)

%load_ext fortranmagicnn%%fortrannsubroutine compute_fortran(x, y, z)n real, intent(in) :: x(:), y(:)n real, intent(out) :: z(size(x, 1))nn z = sin(x + y)nnend subroutine compute_fortrannncompute_fortran([1, 2, 3], [4, 5, 6])n

23、Multicursor支持

Jupyter支持多個Multicursor,類似於Sublime Text。 只需按住Alt鍵並拖動滑鼠即可。

24.、Jupyter-contrib擴展

包括jupyter拼寫檢查器和代碼格式化等。

!pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/mastern!pip install jupyter_nbextensions_configuratorn!jupyter contrib nbextension install --usern!jupyter nbextensions_configurator enable --user n

25、從Jupyter中創建一個演示文稿。

Damian Avilas的RISE允許你從現有的筆記本中創建一個PPT風格的演示文稿。(github.com/damianavila/)

你可以使用conda安裝RISE:

conda install -c damianavila82 risen# Or alternatively pip:nnpip install RISEn# And then run the following code to install and enable the extension:nnjupyter-nbextension install rise --py --sys-prefixnjupyter-nbextension enable rise --py --sys-prefixn

26、Jupyter輸出系統

筆記本顯示為HTML,單元格輸出可以是HTML,因此你可以返回幾乎任何內容:視頻/音頻/圖像。

在這個例子中,我用我的資料庫中的圖像掃描文件夾,並顯示其縮略圖:

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

我們可以用bash命令創建相同的列表

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

27、「大數據」分析

查詢/處理大數據樣本有多種解決方案:

  • ipyparallel(以前的ipython集群)是python中簡單的map-reduce的一個好選擇。我們用它來並行訓練許多機器學習模型(github.com/ipython/ipyp)
  • pyspark(cloudera.com/documentat)
  • spark-sql magic %% sql(github.com/jupyter-incu)

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 dont 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 youre going this route, I highly recommend reading Julius Schulzs excellent article Making publication ready Python notebooks.
  • Create a blog using Pelican from your Jupyter notebooks.

原文:【精心解讀】關於Jupyter Notebook的28個技巧

推薦閱讀:

理解 Python 裝飾器看這一篇就夠了
爬豆瓣電影名的小案例(附視頻操作)
我用Hexo寫博客
從零開始寫Python爬蟲 --- 1.6 爬蟲實踐: DOTA'菠菜'結果查詢
《Python Linux系統管理與自動化運維》收到的評價

TAG:Python | Python入门 | 编程 |