先摘一个官方的定义:

Jupyter Notebook Using Python kernal,so its original name is IPython Notebook, Jupyter notebook is the product of jupiter project which consists of Julia,Python and R, Ruby, C++ .

​ — https://en.wikipedia.org/wiki/Project_Jupyter#Jupyter_Notebook

Jupyter, 旧称为 IPython notebook, 名字由木星Jupiter => Julia + python + R 演变而来,是一个特别的交互式笔记本,本质是一个开源 的 Web 应用程序,用于创建和共享文档,支持可视化代码展示、LaTeX公式、 markdown等,常用于数据科学以及机器学习领域等。

现已全新升级为JupyterLab

jupyter_interface

安装 - Install

1
2
3
4
5
6
7
8
9
10
11
12
## 升级 pip
python -m pip install --upgrade pip

## 安装 jupyterlab
pip install jupyterlab
pip install ipython
jupyter-lab --ip=0.0.0.0

## 也可用conda安装
conda install -c conda-forge jupyterlab

## 安装anaconda即可开箱即用
1
2
3
Successfully built pyrsistent pandocfilters
Installing collected packages: Send2Trash, tornado, MarkupSafe, jinja2, pyzmq, python-dateutil, ipython-genutils, traitlets, jupyter-core, jupyter-client, async-generator, nest-asyncio, pyrsistent, attrs, jsonschema, nbformat, nbclient, pygments, testpath, entrypoints, pyparsing, packaging, bleach, pandocfilters, jupyterlab-pygments, mistune, nbconvert, pywinpty, terminado, prometheus-client, backcall, pickleshare, wcwidth, prompt-toolkit, decorator, parso, jedi, ipython, ipykernel, argon2-cffi, notebook, json5, jupyterlab-server, jupyterlab
...

也可以使用第三方在线的Notebook,比如:

  • 科赛和鲸K-lab(国内):
  • 阿里天池大数据 (国内)
  • 微软Azure notebooks
  • Kaggle
  • Google Colab
  • CoCalc

配置- Config

密码 - Password

首先进入IPython:

1
2
3
4
from notebook.auth import passwd
passwd()
## 然后输入你的密码,比如JuliaRPython
## 输出 'sha1:e74bae0dc7fb:c30542b876ae69581dacec2260463ff98951c98a'

退出Ipython, 在终端打入jupyter lab --generate-config, 以我目前写这个文档的计算机为例,会显示Writing default config to: C:\Users\Administrator\.jupyter\jupyter_notebook_conf ig.py, 配置那个文件,一个密密麻麻的配置文件。

密码的话,修改一下:

修改以下配置:

插件 - Plugins

进入jupyterlab, 点击Settings->Advanced Settings Editor,将false改成true,可看到管理插件的界面,或者呢也可以命令行安装:

1
2
3
4
5
jupyter labextension install @jupyterlab/toc
jupyter labextension install @jupyterlab/latex
jupyter labextension install @jupyter-widgets/jupyterlab-manager
# 查看安装的插件
jupyter labextension list

Python

1
2
%matplotlib inline  # c.IPKernelApp.matplotlib = 'inline'
### for plot
1
2
3
4
5
6
7
8
9
ipython profile create
c = get_config()
c.InteractiveShellApp.exec_lines = [
"import pandas as pd",
"import numpy as np",
"import scipy.stats as spstats",
"import scipy as sp",
"import matplotlib.pyplot as plt"
]

此时你会在~/.ipython/profile_default/目录中获得下面两个文件:

  • ipython_config.py:打开任意ipython kernel时都会运行
  • ipython_notebook_config.py:打开notebook时会运行
1
2
3
4
5
c = get_config()

# Run all nodes in a cell interactively

c.InteractiveShell.ast_node_interactivity = "all"

Styles

~/.jupyter/custom/custom.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
Placeholder for custom user CSS

mainly to be overridden in profile/static/custom/custom.css

This will always be an empty file in IPython
*/
.CodeMirror pre {font-family: Monaco; font-size: 10pt;}
* {font-family: Monaco;}
div.output_area pre {font-family: Monaco; font-size: 10pt;}
div.input_prompt {font-family: Monaco; font-size: 10pt;}
div.out_prompt_overlay {font-family: Monaco; font-size: 10pt;}
div.prompt {font-family: Monaco; font-size: 10pt;}
span.cm-comment {font-family: Monaco !important; font-style:normal !important; color:#FFAE3C !important;}

Magic

1
?str.find()

http://ipython.readthedocs.io/en/stable/interactive/magics.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
!ls *.ipynb
%load ./hello_world.py
%run *.py
%run *.ipynb
%%writefile hello_world.py
%pycat hello_world.py

# this is the string I want to pass to different notebook
%store data
%store -r data

# list all vars
%who str

%%time
%prun

%pdb
plt.hist(x);

%timeit : 计算程序运行时间

1
2
3
4
5
6
7
8
9
10
11
12
13
import time 
def calcProd():
# Calculate the product of the first 100,000 numbers.
product = 1
for i in range(1, 100000):
product = product * i
return product

startTime = time.time()
prod = calcProd()
endTime = time.time()
print('The result is %s digits long.' % (len(str(prod))))
print('Took %s seconds to calculate.' % (endTime - startTime))
1
2
The result is 456569 digits long.
Took 3.17999792098999 seconds to calculate.
1
2
import cProfile
cProfile.run('len(str(prod))')
1
2
3
4
5
6
7
8
9
      4 function calls in 4.334 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 4.334 4.334 4.334 4.334 <string>:1(<module>)
1 0.000 0.000 4.334 4.334 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {built-in method builtins.len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1
2
3
4
5
6
7
%timeit len(str(prod))
# 4.1 s ± 293 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit [x ** 2 for x in range(1, 100000)]
# 37.2 ms ± 784 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit (x ** 2 for x in range(1, 100000))
# 543 ns ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

快捷键

Ctrl + Shift + P

alt + mouse

命令模式 (按键 Esc 开启)

Disable Vimium if installed First

  • Enter : 转入编辑模式
  • F: 查找 替换
  • O : CELL 输出结果 转换
  • K : 选中上方单元
  • J : 选中下方单元
  • Up : 选中上方单元
  • Down : 选中下方单元
  • Shift-M : 合并 CELL
  • Shift-K : 扩大选中上方单元
  • Shift-J : 扩大选中下方单元
  • Shift-Enter : 运行本单元,选中下个单元
  • Ctrl-Enter : 运行本单元
  • Alt-Enter : 运行本单元,在其下插入新单元
  • Y : 单元转入代码状态
  • M :单元转入markdown状态
  • R : 单元转入raw状态
  • 1 : 设定 1 级标题
  • 2 : 设定 2 级标题
  • 3 : 设定 3 级标题
  • 4 : 设定 4 级标题
  • 5 : 设定 5 级标题
  • 6 : 设定 6 级标题
  • A : 在上方插入新单元
  • B : 在下方插入新单元
  • X : 剪切选中的单元
  • C : 复制选中的单元
  • Shift-V : 粘贴到上方单元
  • V : 粘贴到下方单元
  • Z : 恢复删除的最后一个单元
  • D,D : 删除选中的单元
  • Ctrl-S : 文件存盘
  • S : 文件存盘
  • L : 转换行号
  • Shift-O : 转换输出滚动
  • Esc : 关闭页面
  • Q : 关闭页面
  • H : 显示快捷键帮助
  • I,I : 中断Notebook内核
  • 0,0 : 重启Notebook内核
  • Shift : 忽略
  • Shift-Space : 向上滚动
  • Space : 向下滚动

编辑模式 ( Enter 键启动)

  • Tab : 代码补全或缩进
  • Ctrl-/: #
  • Shift-Tab : 提示
  • Ctrl-] : 缩进
  • Ctrl-[ : 解除缩进
  • Ctrl-A : 全选
  • Ctrl-Z : 复原
  • Ctrl-Shift-Z : 再做
  • Ctrl-Y : 再做
  • Ctrl-Home : 跳到单元开头
  • Ctrl-Up : 跳到单元开头
  • Ctrl-End : 跳到单元末尾
  • Ctrl-Down : 跳到单元末尾
  • Ctrl-Left : 跳到左边一个字首
  • Ctrl-Right : 跳到右边一个字首
  • Ctrl-Backspace : 删除前面一个字
  • Ctrl-Delete : 删除后面一个字
  • Esc : 进入命令模式
  • Ctrl-M : 进入命令模式
  • Shift-Enter : 运行本单元,选中下一单元
  • Ctrl-Enter : 运行本单元
  • Alt-Enter : 运行本单元,在下面插入一单元
  • Ctrl-Shift– : 分割单元
  • Ctrl-Shift-Subtract : 分割单元
  • Ctrl-S : 文件存盘
  • Shift : 忽略
  • Up : 光标上移或转入上一单元
  • Down :光标下移或转入下一单元

FAQ

Jupyter ImportError: cannot import name ‘create_prompt_application’

1
2
sudo pip3 uninstall ipython
sudo pip3 install ipython

Try it out, then the error solved for me

1
sudo pip3 install 'prompt-toolkit<2.1.0,>=2.0.0' --force-reinstall

我不小心完全删除了.ipynb文件,如何恢复?

前提是你未删除.ipynb_checkpoints文件夹,可以从中恢复全部代码。(Windows)

REFERENCES

Jupyter

文章

  • @howie6879https://www.jianshu.com/p/88feebf3eb3a(目前已无法打开)

  • @100gle:[在线的 Jupyter Notebook 云环境](在线的 Jupyter Notebook 云环境 - 少数派 (sspai.com)) (可能过时)

    每当我打开在收藏夹里吃灰的数据分析或数据科学的资源时,就会发现每一个教程总是绕不开 **「环境搭建」**的部分。不可否认的是,好的编程环境可以让学习者更好地体验编程学习的乐趣;但环境搭建又往往不可避免的存在很多坑,也许没等一个环境搭建好,就在当中遇到各种奇奇怪怪的问题,学习的兴致早就被报错折磨殆尽了。所以,不得不说环境搭建对于新手而言往往兴趣的 Killer。