Jupyter 简明教程

Jupyter - Quick Guide

IPython - Introduction

Project Jupyter 是用于交互式计算的一套软件产品。IPython 最初是由 Fernando Perez 于 2001 年开发的,作为 Python 解释器增强版。2011 年推出了基于 Web 的 IPython 终端界面,称为 IPython notebook。2014 年,Project Jupyter 开始作为 IPython 的一个分支项目。

Project Jupyter is a suite of software products used in interactive computing. IPython was originally developed by Fernando Perez in 2001 as an enhanced Python interpreter. A web based interface to IPython terminal in the form of IPython notebook was introduced in 2011. In 2014, Project Jupyter started as a spin-off project from IPython.

Jupyter 项目下的软件包包括 −

Packages under Jupyter project include −

  1. Jupyter notebook − A web based interface to programming environments of Python, Julia, R and many others

  2. QtConsole − Qt based terminal for Jupyter kernels similar to IPython

  3. nbviewer − Facility to share Jupyter notebooks

  4. JupyterLab − Modern web based integrated interface for all products.

Python 的标准发行版随 REPL (Read-Evaluate-Print Loop) 环境一起提供,该环境采用 IPython shell 的形式带 >>> 提示符。IPython(即 Interactive Python)是 Python 的增强型交互式环境,它比标准 Python shell 具有更多功能。

Standard distribution of Python comes with a REPL (Read-Evaluate-Print Loop) environment in the form of Python shell with >>> prompt. IPython (stands for Interactive Python) is an enhanced interactive environment for Python with many functionalities compared to the standard Python shell.

Features of IPython

IPython 提供的特性比标准 Python 多。它们如下所述 −

IPython offers more features compared to the standard Python. They are as follows −

  1. Offers a powerful interactive Python shell.

  2. Acts as a main kernel for Jupyter notebook and other front end tools of Project Jupyter.

  3. Possesses object introspection ability. Introspection is the ability to check properties of an object during runtime.

  4. Syntax highlighting.

  5. Stores the history of interactions.

  6. Tab completion of keywords, variables and function names.

  7. Magic command system useful for controlling Python environment and performing OS tasks.

  8. Ability to be embedded in other Python programs.

  9. Provides access to Python debugger.

History and Development

IPython 最初是由 Fernando Perez 于 2001 年开发的。其当前版本是 IPython7.0.1,它需要 Python 3.4 版或更高版。IPython 6.0 是第一个支持 Python 3 的版本。使用 Python 2.7 的用户应使用 IPython 的 2.0 到 5.7 版

IPython was originally developed by Fernando Perez in 2001. Its current version is IPython7.0.1 which requires Python 3.4 version or higher. IPython 6.0 was the first version to support Python 3. Users having Python 2.7 should work with IPython’s version 2.0 to 5.7

计算笔记本的概念始于 80 年代,当时 MATLAB 和 Mathematica 得以发行。面向交互式外壳的这些 GUI 前端具有文本格式化、添加图形、表格以及添加数学符号等功能。Sage Notebook 也是一款基于 Web 的笔记本。

The concept of computational notebooks started in 80s decade when MATLAB and Mathematica were released. These GUI frontends to the interactive shell had features like text formatting, adding graphics, table and adding mathematical symbols. Sage notebook is also a web based notebook.

IPython 的创建者于 2005 年开始为 IPython 外壳的笔记本界面开展工作。IPython Notebook 很快增加了对其他语言(例如 R 和 Julia)的支持。直到 2014 年,Perez 才将 Jupyter 项目作为一个衍生项目从 IPython 中剥离出去,因为 IPython 项目已经变得庞大,其中增加了 Notebook Server 和 Qt 控制台等产品。

Creaters of IPython started working on notebook interface for IPython shell in 2005. IPython notebook soon added support of other languages like R and Julia. It was in 2014, that Perez started Jupyter project as a spin-off project from IPython, since IPython project was becoming big with products like notebook server and Qt console added to it.

自 IPython 4.0 起,所有附加组件都被移至 Project Jupyter 并为 IPython Notebook 增加了对其他语言的支持。IPython 继续专注于改进其增强的解释器功能。它还为 Jupyter Notebook 前端提供主要内核。

Since IPython 4.0, all additional components were shifted to Project Jupyter and adding support of other languages to IPython notebook. IPython continues to focus on improvement of its enhanced interpreter feature. It also provides primary kernel to Jupyter notebook frontend.

IPython - Installation

IPython 默认包含在 Python 的 Anaconda 发行版中。它可以从 Anaconda 的下载页面 www.anaconda.com/download/ 下载。此链接上提供了适用于所有主要操作系统(Windows、MacOS 和 Linux)和架构(32 位和 64 位)的二进制文件。

IPython is included by default in Anaconda distribution of Python. It can be downloaded from Anaconda’s download page www.anaconda.com/download/ Binaries for all major OS (Windows, MacOS and Linux) and architecture (32 bit and 64 bit) are available on this link.

要单独在标准 Python 安装中安装 IPython,您可以使用 pip 命令,如下所示 −

To install IPython separately in standard Python installation, you can use pip command as shown below −

pip3 install ipython

IPython 在内部使用以下软件包 −

IPython internally uses following packages −

Sr.No.

IPython dependencies & Functionality

1

colorama Cross-platform API for printing colored terminal text from Python

2

jedi An autocompletion tool for Python

3

pickleshare Small ‘shelve’ like datastore with concurrency support

4

prompt_toolkit Library for building powerful interactive command lines in Python

5

pygments Syntax highlighting package written in Python

6

simplegeneric Simple generic functions

7

traitlets Configuration system for Python applications.

通常,所有依赖项都将自动安装。否则,您可以使用 pip 单独安装它们。

In general, all dependencies get installed automatically. Else, you can install them individually using pip.

IPython - Getting Started

本章将解释如何开始使用 IPython。

This chapter will explain how to get started with working on IPython.

Starting IPython from Command Prompt.

在深入了解 IPython 之前,请注意代替常规 >>> ,您将看到两个主要的 Python 提示,如下所述 −

Before proceeding to understand about IPython in depth, note that instead of the regular >>>, you will notice two major Python prompts as explained below −

  1. In[1] appears before any input expression.

  2. Out[1] appears before the Output appears.

此外,方括号中的数字自动递增。观察以下屏幕截图以更好地理解 −

Besides, the numbers in the square brackets are incremented automatically. Observe the following screenshot for a better understanding −

ipython cmd

现在,如果您安装了 Python 的 Anaconda 分发,请从开始菜单中打开 Anaconda 提示符。

Now, if you have installed Anaconda distribution of Python, open Anaconda prompt from start menu.

anaconda prompt

Start IPython from conda prompt

与常规 Python 控制台相比,我们会注意到一个区别。IPython 外壳通过对不同的元素(如表达式、函数、变量等)使用不同的颜色方案显示语法高亮。

When compared to regular Python console, we can notice a difference. The IPython shell shows syntax highlighting by using different colour scheme for different elements like expression, function, variable etc.

ipython shell

另一个有用的增强功能是制表符自动补全。我们知道每个对象具有一个或多个方法,如其类中定义的那样。当您在对象前面的点后按 Tab 键时,IPython 会弹出适当的方法列表。

Another useful enhancement is tab completion. We know that each object has one or more methods available as defined in its class. IPython pops up appropriate list of methods as you press tab key after dot in front of object.

在下面的示例中,定义了一个字符串。响应该操作,显示了字符串类的所有方法。

In the following example, a string is defined. As a response, the methods of string class are shown.

string class methods

通过在它的前面输入“?”,IPython 提供任何对象的详细信息。其中包括文档字符串、函数定义和类的构造函数详细信息。例如,要浏览上面定义的字符串对象 var,请在输入提示符中输入 var? 。结果将显示有关其所有详细信息。观察以下屏幕截图以更好地理解 −

IPython provides information of any object by putting ‘?’ in front of it. It includes docstring, function definitions and constructor details of class. For example to explore the string object var defined above, in the input prompt enter var?. The result will show all information about it. Observe the screenshot given below for a better understanding −

ipython info

Magic Functions

IPython 的内置魔术函数极其强大。有两种类型的魔术函数。

IPython’s in-built magic functions are extremely powerful. There are two types of magic functions.

  1. Line magics, which work very much like DOS commands.

  2. Cell magics, which work on multiple lines of code.

我们将在后续章节中详细了解行魔术函数和单元格魔术函数。

We shall learn about line magic functions and cell magic functions in detail in subsequent chapters.

IPython - Running and Editing Python Script

在本章中,让我们了解如何运行和编辑 Python 脚本。

In this chapter, let us understand how to run and edit a Python script.

Run Command

您可以在输入提示中使用 run 命令运行 Python 脚本。run 命令实际上是行 magic 命令,实际上应该写成 %run 。但是, %automagic 模式始终默认打开,因此您可以省略它。

You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.

In [1]: run hello.py
Hello IPython

Edit Command

IPython 还提供编辑 magic 命令。它调用操作系统的默认编辑器。您可以通过 Windows 记事本编辑器将其打开并编辑该脚本。在保存其输入后关闭它之后,将显示已修改脚本的输出。

IPython also provides edit magic command. It invokes default editor of the operating system. You can open it through Windows Notepad editor and the script can be edited. Once you close it after saving its input, the output of modified script will be displayed.

In [2]: edit hello.py
Editing... done. Executing edited code...
Hello IPython
welcome to interactive computing

请注意,hello.py 最初仅包含一个语句,在编辑后又添加了一个语句。如果未向编辑命令提供文件名,则会创建一个临时文件。观察以下显示相同内容的代码。

Note that hello.py initially contained only one statement and after editing one more statement was added. If no file name is given to edit command, a temporary file is created. Observe the following code that shows the same.

In [7]: edit
IPython will make a temporary file named:
C:\Users\acer\AppData\Local\Temp\ipython_edit_4aa4vx8f\ipython_edit_t7i6s_er.py
Editing... done. Executing edited code...
magic of IPython
Out[7]: 'print ("magic of IPython")'

IPython - History Command

IPython 保存当前会话中的命令及其结果。我们可以按向上键和向下键滚动浏览之前的命令。

IPython preserves both the commands and their results of the current session. We can scroll through the previous commands by pressing the up and down keys.

此外,最后三个输出对象存储在特殊变量 , _ and _ 中。 history 魔术命令显示当前会话中的上一条命令,如下图中的屏幕截图所示 −

Besides, last three objects of output are stored in special variables , _ and _. The history magic command shows previous commands in current session as shown in the screenshot given below −

history command

IPython - System Commands

如果输入单元格中的语句以惊叹号 (!) 开头,则它会被当作底层操作系统的系统命令。例如, !ls (适用于 Linux)和 !dir (适用于 Windows)会显示当前目录的内容

If the statement in the input cell starts with the exclamation symbol (!), it is treated as a system command for underlying operating system. For example, !ls (for linux) and !dir (for windows) displays the contents of current directory

exclamation symbol command

系统命令的输出还可以像下面所示分配给 Python 变量 −

The output of system command can also be assigned to a Python variable as shown below −

output system command

该变量存储无颜色的输出,并在换行符处拆分。

The variable stores output without colors and splits at newline characters.

还可以将 Python 变量或表达式和系统命令调用结合起来。大括号 {} 中的变量可以内嵌在命令文本中。观察以下示例 −

It is also possible to combine Python variables or expressions with system command calls. Variable in curly brackets {} can be embedded in command text. Observe the following example −

system command calls

以下是另一个示例,它说明在 Python 变量前加上 $ 也能实现相同的结果。

Here is another example to understand that prefixing Python variable with $ also achieves the same result.

prefixing python variable

IPython - Command Line Options

在本章中,让我们了解如何使用 IPython 中的各种命令行选项。

In this chapter, let us understand how to work with various command line options in IPython.

Invoking IPython Program

你可以使用以下选项调用 IPython 程序:

You can invoke an IPython program using the following options −

C:\python36> ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg]

file 选项是一个 Python 脚本,扩展名为 .py。如果没有给出其他选项,将执行该脚本并重新显示命令提示符。

The file option is a Python script with .py extension. If no other option is given, the script is executed and command prompt reappears.

C:\python36>ipython hello.py
Hello IPython
welcome to interactive computing

Subcommands and Parameters

IPython 命令接受以下子命令选项:

An IPython command accepts the following subcommand options −

  1. Profile − Create and manage IPython profiles.

  2. Kernel − Start a kernel without an attached frontend.

  3. Locate − Print the path to the IPython dir.

  4. History − Manage the IPython history database.

IPython 配置文件子命令接受以下参数:

An IPython profile subcommand accepts the following parameters −

  1. ipython profile create myprofile − Creates a new profile.

  2. ipython profile list − Lists all available profiles.

  3. ipython locate profile myprofile − Locates required profile.

要安装新的 IPython 内核,请使用以下命令 −

To install new IPython kernel, use the following command −

Ipython kernel –install –name

要打印出 IPython 目录的路径,请使用以下命令 −

To print the path to the IPython dir, use the following command −

C:\python36>ipython locate myprofile
C:\Users\acer\.ipython

此外,我们还知道 −

Besides, we know that −

  1. The history subcommand manages IPython history database.

  2. The trim option reduces the IPython history database to the last 1000 entries.

  3. The clear option deletes all entries.

以下列出了 IPython 的其他一些重要的命令行选项 −

Some of the other important command line options of IPython are listed below −

Sr.No.

IPython Command & Description

1

--automagic Turn on the auto calling of magic commands.

2

--pdb Enable auto calling the pdb debugger after every exception.

3

--pylab Pre-load matplotlib and numpy for interactive use with the default matplotlib backend.

4

--matplotlib Configure matplotlib for interactive use with the default matplotlib backend.

5

--gui=options Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk2','gtk3', 'osx', 'pyglet', 'qt', 'qt4', 'qt5', 'tk', 'wx', 'gtk2', 'qt4').

某些 IPython 命令行选项的示例用法显示在以下表格中 −

The sample usage of some of the IPython command line options are shown in following table −

Sr.No.

IPython Command & Description

1

ipython --matplotlib enable matplotlib integration

2

ipython --matplotlib=qt enable matplotlib integration with qt4 backend

3

ipython --profile=myprofile start with profile foo

4

ipython profile create myprofile create profile foo w/ default config files

5

ipython help profile show the help for the profile subcmd

6

ipython locate print the path to the IPython directory

7

ipython locate profile myprofile print the path to the directory for profile myprofile

IPython - Dynamic Object Introspection

IPython 有不同的方法可以动态获取有关 Python 对象的信息。在本章中,让我们学习如何在 IPython 中进行动态对象自省。

IPython has different ways of obtaining information about Python objects dynamically. In this chapter, let us learn the ways of dynamic object introspection in IPython.

使用 ??? 提供有关对象具体而更详细的信息。在下文讨论的第一个示例中,创建了一个简单的整数对象 a。可以通过在输入单元格中输入 a? 来获取其信息。

Use of ? and ?? provides specific and more detailed information about the object. In the first example discussed below, a simple integer object a is created. Its information can be procured by typing a ? in the input cell.

dynamic object introspection

在第二个示例中,让我们定义一个函数,并使用 ??? 对此函数对象进行自省。

In the second example, let us define a function and introspect this function object with ? and ??.

function and introspect

请注意,魔术函数 %psearch 等同于使用 ??? 来获取对象信息。

Note that the magic function %psearch is equivalent to the use of ? or ?? for fetching object information.

IPython - IO Caching

IPython 控制台上的输入和输出单元按序编号。在本章中,我们将详细了解 Python 中的 IO 缓存。

The input and output cells on IPython console are numbered incrementally. In this chapter, let us look into IO caching in Python in detail.

在 IPython 中,使用向上箭头键检索输入。此外,所有先前的输入均已保存且可以检索。变量 _i_i__i 始终存储前三个输入条目。此外, In_in 变量提供所有输入的列表。显然, _in[n] 从第 n 个输入单元检索输入。以下 IPython 会话将帮助您理解这一现象 −

In IPython, inputs are retrieved using up arrow key. Besides, all previous inputs are saved and can be retrieved. The variables _i, _i, and __i always store the previous three input entries. In addition, In and _in variables provides lists of all inputs. Obviously _in[n] retrieves input from nth input cell. The following IPython session helps you to understand this phenomenon −

In [1]: print ("Hello")
Hello

In [2]: 2+2
Out[2]: 4

In [3]: x = 10

In [4]: y = 2

In [5]: pow(x,y)
Out[5]: 100

In [6]: _iii, _ii, _i
Out[6]: ('x = 10', 'y = 2', 'pow(x,y)')

In [7]: In
Out[7]:
['',
   'print ("Hello")',
   '2+2',
   'x = 10',
   'y = 2',
   'pow(x,y)',
   '_iii, _ii, _i',
   'In'
]

In [8]: In[5] 9. IPython — IO
Out[8]: 'pow(x,y)'

In [9]: _ih
Out[9]:
['',
   'print ("Hello")',
   '2+2',
   'x = 10',
   'y = 2',
   'pow(x,y)',
   '_iii, _ii, _i',
   'In',
   'In[5]',
   '_ih'
]

In [11]: _ih[4]
Out[11]: 'y = 2'

In [12]: In[1:4]
Out[12]: ['print ("Hello")', '2+2', 'x=10']

类似地,单下划线、双下划线和三下划线用作变量以存储前三个输出。 Out_oh 还形成单元格编号和执行操作的单元格输出的词典对象(不包括赋值语句)。要检索特定输出单元格的内容,请使用 Out[n]_oh[n] 。您还可以使用切片获取范围内的输出单元格。

Similarly, single, double and triple underscores act as variables to store previous three outputs. Also Out and _oh form a dictionary object of cell number and output of cells performing action (not including assignment statements). To retrieve contents of specific output cell, use Out[n] or _oh[n]. You can also use slicing to get output cells within a range.

In [1]: print ("Hello")
Hello

In [2]: 2+2
Out[2]: 4

In [3]: x = 10

In [4]: y = 3

In [5]: pow(x,y)
Out[5]: 1000

In [6]: ___, __, _
Out[6]: ('', 4, 1000)

In [7]: Out
Out[7]: {2: 4, 5: 1000, 6: ('', 4, 1000)}

In [8]: _oh
Out[8]: {2: 4, 5: 1000, 6: ('', 4, 1000)}

In [9]: _5
Out[9]: 1000

In [10]: Out[6]
Out[10]: ('', 4, 1000)

Setting IPython as Default Python Environment

不同的环境变量会影响 Python 的行为。PYTHONSTARTUP 环境变量被分配给一个 Python 脚本。实际上,该脚本将在 Python 提示符出现之前执行。如果在每次新的 Python 会话启动时都要默认加载某些模块,此方法就很有用。

Different environment variables influence Python’s behaviour. PYTHONSTARTUP environment variable is assigned to a Python script. As an effect, this script gets executed before Python prompt appears. This is useful if certain modules are to be loaded by default every time a new Python session starts.

以下脚本 (start.py) 导入 IPython 模块,并执行 start_ipython() 函数,以便在调用 Python 可执行文件时用 IPython shell 替换默认 Python shell with prompt (>>>)

The following script (start.py) imports IPython module and executes start_ipython() function to replace default Python shell with prompt (>>>) by IPython shell when Python executable is invoked.

import os, IPython
os.environ['PYTHONSTARTUP'] = ''
IPython.start_ipython()
raise SystemExit

假设此文件存储在 Python 的安装目录 (c:\python36) 中,请设置 PYTHONSTARTUP 环境变量并从命令行启动 Python。然后,IPython shell 就会像下面所示出现 −

Assuming that this file is stored in Python’s installation directory (c:\python36), set PYTHONSTARTUP environment variable and start Python from command line. Then IPython shell appears as shown below −

python installation directory

请注意,可以在 Windows 中使用系统属性对话框,在 Linux 上使用 export 命令永久设置环境变量。

Note that the environment variable can be permanently set using System Properties dialog in Windows and using export command on Linux.

IPython - Importing Python Shell Code

IPython 可以从带有默认 >>> 提示符的标准 Python 控制台和另一个 IPython 会话中读取内容。以下屏幕截图显示在标准 Python shell 中编写的 for 循环 −

IPython can read from standard Python console with default >>> prompt and another IPython session. The following screenshot shows a for loop written in standard Python shell −

standard python shell loop

复制代码(连同 Python 提示符),并将其粘贴到 IPython 输入单元格中。IPython 会智能地滤出输入提示符 (>>> 和 …​) 或 IPython 提示符 (In [N]: 和 …​:)

Copy the code (along with Python prompt) and paste the same in IPython input cell. IPython intelligently filters out the input prompts (>>> and …​) or IPython ones (In [N]: and …​:)

ipython input cell

同样,来自一个 IPython 会话的代码也可以粘贴到另一个会话中。下面给出的第一个屏幕截图显示在一个 IPython 窗口中定义 SayHello() 函数 −

Similarly, code from one IPython session can be pasted in another. The first screenshot given below shows definition of SayHello() function in one IPython window −

ipython window

现在,让我们选择代码并粘贴到另一个 IPython shell 中并调用 SayHello() 函数。

Now, let us select the code and paste in another IPython shell and call SayHello() function.

ipython shell cmd

Embedding IPython

IPython 模块的 embed() 函数使得在 Python 代码的名称空间中嵌入 IPython 成为可能。因此,你可以在默认的 Python 环境中利用 IPython 的特性,例如对象自省和 tab 补全。

The embed() function of IPython module makes it possible to embed IPython in your Python codes’ namespace. Thereby you can leverage IPython features like object introspection and tab completion, in default Python environment.

ipython module

在嵌入之前存在于全局名称空间的 Python 对象将可供 IPython 使用。

Python objects present in the global namespace before embedding, will be available to IPython.

python objects

如果在 IPython 中创建了新对象或修改了以前的对象,则在退出 IPython 后,它们将自动可供默认环境使用。嵌入的 IPython shell 不会改变先前代码或对象的状态。

If new objects are formed while in IPython or previous objects are modified, they will be automatically available to default environment after exiting IPython. Embedded IPython shell doesn’t change the state of earlier code or objects.

但是,如果 IPython 嵌入在函数内的局部名称空间中,则其中的对象在关闭后将不可用。在这里,我们定义了一个 add() 函数。在 add() 内部,我们调用 IPython 声明一个变量。如果我们尝试在 IPython 关闭后访问变量,将引发 NameError 异常。

However, if IPython is embedded in local namespace like inside a function, the objects inside it will not be available once it is closed. Here, we have defined a function add(). Inside add() we invoke IPython and declared a variable. If we try to access variable in IPython after it is closed, NameError exception will be raised.

ipython nameerror exception

IPython - Magic Commands

与标准 Python 外壳相比,魔术命令或魔术函数是 IPython 提供的重要增强功能之一。这些魔术命令旨在使用 Python 来解决数据分析中的常见问题。事实上,它们控制着 IPython 本身的行为。

Magic commands or magic functions are one of the important enhancements that IPython offers compared to the standard Python shell. These magic commands are intended to solve common problems in data analysis using Python. In fact, they control the behaviour of IPython itself.

当 Python 语法不是最自然时,魔术命令可作为方便的功能。它们可用于在其工作流程中嵌入无效 Python 语法。

Magic commands act as convenient functions where Python syntax is not the most natural one. They are useful to embed invalid python syntax in their work flow.

Types of Magic Commands

魔术命令有两种类型 −

There are two types of magic commands −

  1. Line magics

  2. Cell magics

Line Magics

它们类似于命令行调用。它们以 % 字符开头。该行的其余部分是其在没有括号或引号的情况下传递的参数。行魔术可作为表达式使用,其返回值可被分配给变量。

They are similar to command line calls. They start with % character. Rest of the line is its argument passed without parentheses or quotes. Line magics can be used as expression and their return value can be assigned to variable.

Cell Magics

它们有一个 %% 字符前缀。与行魔术函数不同,它们可以在其调用下方的多行中操作。事实上,它们可以对其接收的输入进行任意修改,而输入甚至不必是有效的 Python 代码。它们将整个块作为单个字符串接收。

They have %% character prefix. Unlike line magic functions, they can operate on multiple lines below their call. They can in fact make arbitrary modifications to the input they receive, which need not even be a valid Python code at all. They receive the whole block as a single string.

要了解有关魔术函数、内置魔术及其文档字符串的更多信息,请使用魔术命令。特定魔术函数的信息可通过 % magicfunction? 命令获取。让我们现在描述一些内置行和单元格魔术命令。

To know more about magic functions, the built-in magics and their docstrings, use the magic command. Information of a specific magic function is obtained by %magicfunction? Command. Let us now describe some of the built-in line and cell magic commands.

Built-in line magics

%autocall [mode]

此魔术函数可以自动调用函数,而无需使用括号。它需要三个可能的模式参数: 0 (off), 1 (smart) is default2 (always on)

This magic function makes a function automatically callable without having to use parentheses. It takes three possible mode parameters: 0 (off), 1 (smart) is default or 2 (always on).

built in line magics

%automagic

如果设置为 1,则魔术函数在无需输入初始 % 的情况下可变为可调用。没有参数时,它会切换开/关。要停用,请设置为 0。

Magic functions are callable without having to type the initial % if set to 1. Without arguments it toggles on/off. To deactivate, set to 0.

以下示例显示了在将 %automagic 设置为 1 时,调用了不带前导 % 的魔术函数 %pwd (显示当前工作目录)

The following example shows a magic function %pwd (displays present working directory) being called without leading % when %automagic set to 1

automagic

%cd

该行魔术改变了当前目录。该命令会在 IPython 会话期间自动维护您访问的一个内部目录列表,并在变量 _dh 中。您还可以执行 ‘cd -<tab>’ 来方便地查看目录历史记录。

This line magic changes the current directory. This command automatically maintains an internal list of directories you visit during your IPython session, in the variable _dh. You can also do ‘cd -<tab>’ to see directory history conveniently.

cd

Usage

%cd 命令可以用以下方式使用 −

The %cd command can be used in the following ways −

  1. %cd <dir> − Changes current working directory to <dir>

  2. %cd.. − Changes current directory to parent directory

  3. %cd − changes to last visited directory.

%dhist

该魔术命令会打印您在当前会话中访问过的所有目录。每当使用 %cd 命令时,此列表都会在 _dh 变量中更新。

This magic command prints all directories you have visited in current session. Every time %cd command is used, this list is updated in _dh variable.

dhist

%edit

该魔术命令会调用当前操作系统(Windows 的记事本)的默认文本编辑器来编辑 Python 脚本。脚本在关闭编辑器后执行。

This magic command calls upon the default text editor of current operating system (Notepad for Windows) for editing a Python script. The script is executed as the editor is closed.

%env

该魔术命令将列出所有环境变量。它还会读取特定变量的值或设置环境变量的值。

This magic command will list all environment variables. It also reads value of particular variable or set the value of environment variable.

Usage

Usage

%cd 命令可以用以下方式使用 −

The %cd command can be used in the following ways −

  1. %env − Lists all environment variables

  2. %env var − Gets value for var

  3. %env var val − Sets value for var

env

%gui [GUINAME]

当不带参数使用该命令时,它将启用或禁用 IPython GUI 事件循环集成。通过 GUINAME 参数,该魔术可以将默认 GUI 工具包替换为指定的一个。

When used without argument this command enables or disables IPython GUI event loop integration. With GUINAME argument, this magic replaces the default GUI toolkits by the specified one.

Sr.No.

Command & Description

1

%gui wx enable wxPython event loop integration

2

*%gui qt4

qt* enable PyQt4 event loop integration

3

%gui qt5 enable PyQt5 event loop integration

4

%gui gtk enable PyGTK event loop integration

5

%gui gtk3 enable Gtk3 event loop integration

6

%gui tk enable Tk event loop integration

7

%gui osx enable Cocoa event loop integration

8

(requires %matplotlib 1.1)

9

%lsmagic

显示当前可用的所有魔术函数

Displays all magic functions currently available

lsmagic

%matplotlib

此函数在 IPython 会话中激活 Matplotlib 交互式支持。但是,它不会导入 Matplotlib 库。Matplotlib 默认 GUI 工具包是 TkAgg。但您可以显式请求不同的 GUI 后端。您可以看到可用后端的列表,如下所示 −

This function activates matplotlib interactive support during an IPython session. However, it does not import matplotlib library. The matplotlib default GUI toolkit is TkAgg. But you can explicitly request a different GUI backend. You can see a list of the available backends as shown −

In [4]: %matplotlib --list
Available matplotlib backends:
['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg','gtk', 'tk', 'inline']

此处所示的 IPython 会话使用 qt 工具包绘制正弦波 −

The IPython session shown here plots a sine wave using qt toolkit −

matplotlib

在使用 Jupyter notebook 时,%matplotlib inline 指令仅在浏览器中显示绘图输出。

While using Jupyter notebook, %matplotlib inline directive displays plot output in the browser only.

%notebook

此函数将当前 IPython 历史记录转换为具有 ipynb 扩展名的 IPython notebook 文件。上一个示例中的输入单元格保存为 sine.ipynb

This function converts current IPython history into an IPython notebook file with ipynb extension. The input cells in previous example are saved as sine.ipynb

%notebook sine.ipynb

%pinfo

此函数类似于对象自省 ? 字符。要获取有关对象的的信息,请使用以下命令 −

This function is similar to object introspection ? character. To obtain information about an object, use the following command −

%pinfo object

这与 object??object 同义。

This is synonymous to object? or ?object.

%precision

此魔术函数将浮点结果限制为十进制小数后的指定位数。

This magic function restricts a floating point result to specified digits after decimal.

precision

%pwd

此魔术函数返回当前工作目录。

This magic function returns the present working directory.

pwd

%pylab

此函数用 Matplotlib 和 numpy 库填充当前 IPython 会话。

This function populates current IPython session with matplotlib, and numpy libraries.

pylab

%recall

在不带任何参数的情况下执行时,此函数执行上一个命令。

When executed without any parameter, this function executes previous command.

请注意,在 %recall n 中,前面的数字是输入单元格编号。因此,单元格 n 中的命令被调用。您可以通过使用诸如 %recall 1-4 之类的命令来调用部分单元格中的命令。当前输入单元格由调用的单元格填充,并且光标闪烁,直至按下回车键。

Note that in %recall n, number in front of it is input cell number. Hence the command in the nth cell is recalled. You can recall commands in section of cells by using command such as %recall 1-4. Current input cell is populated with recalled cell and the cursor blinks till the enter key is pressed.

recall

%run

此命令从 IPython shell 运行 Python 脚本。

This command runs a Python script from within IPython shell.

run

%time

此命令显示 IPython 环境执行 Python 表达式所需的时间。

This command displays time required by IPython environment to execute a Python expression.

time

%timeit

此函数还显示 IPython 环境执行 Python 表达式所需的时间。Python 语句或表达式的执行时间使用 timeit 模块。此函数可同时用作行魔术和单元格魔术,如下所述 −

This function also displays time required by IPython environment to execute a Python expression. Time execution of a Python statement or expression uses the timeit module. This function can be used both as a line and cell magic as explained here −

  1. In line mode you can time a single-line.

  2. In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code.

%who

这种行魔术打印所有交互变量,并带有一些最少格式。如果给出任何参数,则仅打印类型与其中之一匹配的变量。

This line magic prints all interactive variables, with some minimal formatting. If any arguments are given, only variables whose type matches one of these are printed.

who

IPython Custom Line Magic function

IPython 的核心库包含 register_line_magic 装饰器。用户自定义函数使用此装饰器转换成行魔术函数。

IPython’s core library contains register_line_magic decorator. A user defined function is converted into a line magic function using this decorator.

ipython line magic function

Project Jupyter - Overview

Jupyter 项目始于 2014 年 IPython 项目的分支。IPython 与语言无关的特性被移到了 Jupyter 这个名字下。这个名字指的是 Jupyter 支持的核心编程语言,即 Julia、Python和R。Jupyter 项目下的产品旨在支持交互式数据科学和科学计算。

Project Jupyter started as a spin-off from IPython project in 2014. IPython’s language-agnostic features were moved under the name – Jupyter. The name is a reference to core programming languages supported by Jupyter which are Julia, Python and RProducts under Jupyter project are intended to support interactive data science and scientific computing.

Jupyter 项目由以下各种产品组成:

The project Jupyter consists of various products described as under −

  1. IPykernel − This is a package that provides IPython kernel to Jupyter.

  2. Jupyter client − This package contains the reference implementation of the Jupyter protocol. It is also a client library for starting, managing and communicating with Jupyter kernels.

  3. Jupyter notebook − This was earlier known as IPython notebook. This is a web based interface to IPython kernel and kernels of many other programming languages.

  4. Jupyter kernels − Kernel is the execution environment of a programming language for Jupyter products.

下面给出 Jupyter 内核列表:

The list of Jupyter kernels is given below −

Kernel

Language

URL

IJulia

Julia

https://github.com/JuliaLang

IHaskell

Haskell

https://github.com/gibiansky

IRuby

Ruby

https://github.com/SciRuby/iruby

IJavaScript

JavaScript

https://github.com/n-riesco

IPHP

PHP

https://github.com/dawehner

IRKernel

R

http://irkernel.github.io/

  1. Qtconsole − A rich Qt-based console for working with Jupyter kernels

  2. nbconvert − Converts Jupyter notebook files in other formats

  3. JupyterLab − Web based integrated interface for notebooks, editors, consoles etc.

  4. nbviewer − HTML viewer for notebook files

Jupyter Notebook - Introduction

IPython Notebook 由 Fernando Perez 开发,作为 IPython 内核的基于 Web 的前端。为了构建面向多种语言的集成交互式计算环境,Notebook 项目被移至 Project Jupyter 下,除了 Python 之外,还针对 Juila 和 R 编程环境提供前端。

IPython notebook was developed by Fernando Perez as a web based front end to IPython kernel. As an effort to make an integrated interactive computing environment for multiple language, Notebook project was shifted under Project Jupyter providing front end for programming environments Juila and R in addition to Python.

Notebook 文档包含带有 HTML 格式化文本、图形、数学方程式等内容的富文本元素。该 Notebook 还是一份可执行文件,其中包含 Python 或其他支持语言的代码块。

A notebook document consists of rich text elements with HTML formatted text, figures, mathematical equations etc. The notebook is also an executable document consisting of code blocks in Python or other supporting languages.

Jupyter Notebook 是一种客户端-服务器应用程序。该应用程序在本地计算机上启动服务器,并在 Web 浏览器中打开 Notebook 界面,用户可以在其中对其进行编辑并从中运行。该 Notebook 被保存为 ipynb 文件,并可以导出为 html、pdf 和 LaTex 文件。

Jupyter notebook is a client-server application. The application starts the server on local machine and opens the notebook interface in web browser where it can be edited and run from. The notebook is saved as ipynb file and can be exported as html, pdf and LaTex files.

Working with Jupyter Online

如果你对 Jupyter 不熟悉,可以在本地计算机上安装之前尝试 Jupyter notebook 的功能。为此,访问浏览器中的 ` https://jupyter.org `,然后选择 ` ‘Try Jupyter with Python’ ` 选项。

If you are new to Jupyter, you can try features of Jupyter notebook before installing on your local machine. For this purpose, visit https://jupyter.org in your browser and choose ‘Try Jupyter with Python’ option.

try jupyter with python

这将在浏览器中打开 ` https://mybinder.org ` 的主页。从 File 菜单中选择新建笔记本选项,在浏览器中打开一个空白的 Jupyter。与 IPython 终端类似的输入单元格将显示。你可以在其中执行任何 Python 表达式。

This will open home page of https://mybinder.org From the File menu, choose new notebook option to open a blank Jupyter in your browser. The input cell, as similar to that in IPython terminal, will be displayed. You can execute any Python expression in it.

jupyter new notebook

Installation and Getting Started

你还可以使用 pip 包管理器轻松安装 Jupyter notebook 应用程序。

You can easily install Jupyter notebook application using pip package manager.

pip3 install jupyter

要启动应用程序,请在命令提示符窗口中使用以下命令。

To start the application, use the following command in the command prompt window.

c:\python36>jupyter notebook

服务器应用程序开始在默认端口号 8888 上运行,浏览器窗口打开以显示笔记本仪表板。

The server application starts running at default port number 8888 and browser window opens to show notebook dashboard.

jupyter notebook dashboard

请注意,仪表板在新按钮旁的浏览器右边界附近显示了一个下拉菜单,旁边带有箭头。它包含当前可用的 notebook 内核。现在,选择 Python 3,然后在一个新选项卡中打开一个新的 notebook。与 IPython 控制台中类似的输入单元格显示。

Observe that the dashboard shows a dropdown near the right border of browser with an arrow beside the New button. It contains the currently available notebook kernels. Now, choose Python 3, then a new notebook opens in a new tab. An input cell as similar to that of in IPython console is displayed.

你可以在其中执行任何 Python 表达式。结果将显示在 Out 单元格中。

You can execute any Python expression in it. The result will be displayed in the Out cell.

result out cell

Jupyter Notebook - Dashboard

Jupyter Notebook 的仪表板包含三个选项卡,如下面的屏幕截图所示:

The dashboard of Jupyter Notebook contains three tabs as shown in the screenshot given below −

jupyter dashboard

Files Tab

“文件”选项卡显示笔记本应用从其调用的当前目录下的文件和文件夹。当前打开的笔记本对应的行和正在运行的状态显示在最后一列修改的旁边。它还显示了 Upload 按钮,可以使用该按钮将文件上载到笔记本服务器。

The "Files" tab displays files and folders under current directory from which notebook app was invoked. The row corresponding to a notebook which is currently open and the running status is shown just beside the last modified column. It also displays Upload button using which a file can be uploaded to notebook server.

Running Tab

“正在运行”选项卡显示当前正在运行哪些笔记本。

The "Running" tab shows which of the notebooks are currently running.

Cluster Tab

第三个选项卡“群集”由 IPython parallel 提供。IPython 的并行计算框架,是 IPython 内核的扩展版本。

The third tab, "Clusters", is provided by IPython parallel. IPython’s parallel computing framework, an extended version of the IPython kernel.

从 New 下拉菜单中选择 Terminal 打开 cmd 窗口。你现在可以在此处启动 IPython 终端。

From the New dropdown choose Terminal to open a cmd window. You can now start an IPython terminal here.

ipython terminal

Jupyter Notebook - User Interface

在 Jupyter 的用户界面中,在标题栏的徽标旁边显示文件名。

In the user interface of Jupyter, just beside the logo in the header, the file name is displayed.

jupyter filename creation

你可以在标题栏下方找到菜单栏。每个菜单都包含许多选项,将在以后讨论。

You can find the menu bar below the header. Each menu contains many options that will be discussed later.

jupyter notebook menubar

构成工具栏的图标行可帮助用户执行通常需要执行的操作

A row of icons forming toolbar helps user to perform often required operations

jupyter notebook toolbar

笔记具有两种模式 - Command modeEdit mode 。当某个单元格被单击时,笔记本会进入编辑模式。请注意这个铅笔符号就在内核名称旁边。

The notebook has two modes − Command mode and Edit mode. Notebook enters edit mode when a cell is clicked. Notice the pencil symbol just besides name of kernel.

jupyter notebook editmode

内核指示符符号就显示在内核名称的右侧。请注意:空心圆表示内核空闲,实心圆表示内核繁忙。

Kernel indicator symbol is displayed just to the right of kernel name. Note that a hollow circle means kernel is idle and solid circle means it is busy.

jupyter notebook kernel indicator

File Menu

以下是在文件菜单中提供的选项 -

The following are the options available in the File menu −

Sr.No.

File menu & Description

1

New notebook choose the kernel to start new notebook

2

Open Takes user to dashboard to choose notebook to open

3

Save as save current notebook and start new kernel

4

Rename rename current notebook

5

Save saves current notebook and stores current checkpoint

6

Revert reverts state of notebook to earlier checkpoint

7

Download export notebook in one of various file formats

下面显示了可用的文件格式:

The file formats that are available are shown below −

file formats

Edit Menu

编辑菜单包含可以执行剪切、复制和粘贴单元格、删除选定的单元格、拆分和合并单元格、在笔记本中找到并替换、剪切/复制附件和插入图像的按钮。

Edit menu consists of buttons to perform cut, copy and paste cells, delete selected cell, split and merge cells, move cells up and down, find and replace within notebook, cut/copy attachments and insert image.

View Menu

这些菜单中的按钮可以帮助我们隐藏/显示标题、工具栏和单元格编号。

Buttons in this menu help us to hide/display header, toolbar and cell numbers.

Insert Menu

此菜单为您提供了在当前单元格之前或之后插入单元格的选项。

This menu gives you options for inserting cell before or after the current cell.

Cell Menu

此菜单中的选项允许用户在笔记本中运行所有或特定单元格。您还可以将单元类型设置为代码类型、标记或原始 nbconvert 类型。

The options in this menu let user run all or specific cells in the notebook. You can also set the cell type to code type, markdown or raw nbconvert type.

Kernel Menu

您可以从这个菜单中启动、中断、重启或者关闭内核。您还可以启动一个新的内核。

From this menu you can start, interrupt, restart or shutdown the kernel. You can also start a new kernel.

Widgets Menu

您可以从这个菜单中保存、清除、下载或者内嵌部件状态。

From this menu you can save, clear, download or embed widget state.

Help menu

此菜单显示各种预定义的键盘快捷键。您还可以按您的方便编辑快捷键。

Various predefined keyboard shortcuts are displayed from this menu. You can also edit the shortcuts as per your convenience.

Jupyter Notebook - Types of Cells

Jupyter Notebook 中的单元格有三种类型 − Code, MarkdownRaw

Cells in Jupyter notebook are of three types − Code, Markdown and Raw.

Code Cells

此单元格中的内容将作为当前内核的编程语言中的语句处理。默认内核为 Python。所以,我们可以在代码单元格中写 Python 语句。当此单元格运行时,它的结果将显示在一个输出单元格中。输出可能是文本、图片、matplotlib 图表或 HTML 表格。代码单元格具有富文本功能。

Contents in this cell are treated as statements in a programming language of current kernel. Default kernel is Python. So, we can write Python statements in a code cell. When such cell is run, its result is displayed in an output cell. The output may be text, image, matplotlib plots or HTML tables. Code cells have rich text capability.

Markdown Cells

这些单元格包含使用 markdown 语言格式化的文本。可以使用所有类型的格式化功能,如加粗和倾斜文本、显示有序或无序列表、呈现表格化内容等。Markdown 单元格特别适用于为 notebook 的计算过程提供文档。

These cells contain text formatted using markdown language. All kinds of formatting features are available like making text bold and italic, displaying ordered or unordered list, rendering tabular contents etc. Markdown cells are especially useful to provide documentation to the computational process of the notebook.

Raw Cells

原始单元格中的内容未由 notebook 内核评估。当通过 nbconvert 传递时,它们将按需要呈现。如果您在原始单元格中输入 LatEx,则在应用 nbconvert 后将进行渲染。

Contents in raw cells are not evaluated by notebook kernel. When passed through nbconvert, they will be rendered as desired. If you type LatEx in a raw cell, rendering will happen after nbconvert is applied.

raw cells

Jupyter Notebook - Editing

虽然菜单栏和工具栏允许你在笔记本上执行各种操作,但最好能使用键盘快捷键快速执行它们。

While the menu bar and toolbar lets you perform various operations on notebook, it is desirable to be able to use keyboard shortcuts to perform them quickly.

Jupyter 笔记本有两个不同的键盘输入模式 −

Jupyter Notebooks have two different keyboard input modes −

  1. Command Mode − Binds the keyboard to notebook level actions. Indicated by a grey cell border with a blue left margin.

  2. Edit Mode − When you are typing in a cell. Indicated by a green cell border.

命令模式(按 Esc 启用)

Command Mode (press Esc to enable)

F

find and replace

1

change cell to heading 1

Ctrl-Shift-F

open the command palette

2

change cell to heading 2

Ctrl-Shift-P

open the command palette

3

change cell to heading 3

Enter

enter edit mode

4

change cell to heading 4

P

open the command palette

5

change cell to heading 5

Shift-Enter

run cell, select below

6

change cell to heading 6

Ctrl-Enter

run selected cells

A

insert cell above

Alt-Enter

run cell and insert below

B

insert cell below

Y

change cell to code

X

cut selected cells

M

change cell to markdown

C

copy selected cells

R

change cell to raw

V

paste cells below

K

select cell above

Z

undo cell deletion

Up

select cell above

D,D

delete selected cells

Down

select cell below

Shift-M

merge selected cells, or current cell with cell below if only one cell is selected

J

select cell below

Shift-V

paste cells above

Shift-K

extend selected cells above

L

toggle line numbers

Shift-Up

extend selected cells above

O

toggle output of selected cells

Shift-Down

extend selected cells below

Shift-O

toggle output scrolling of selected cells

Shift-J

extend selected cells below

I,I

interrupt the kernel

Ctrl-S

Save and Checkpoint

0,0

restart the kernel (with dialog)

S

Save and Checkpoint

Esc

close the pager

Shift-L

toggles line numbers in all cells, and persist the setting

Q

close the pager

Shift-Space

scroll notebook up

Space

scroll notebook down

编辑模式(按 Enter 启用)

Edit Mode (press Enter to enable)

Tab

code completion or indent

Ctrl-Home

go to cell start

Shift-Tab

tooltip

Ctrl-Up

go to cell start

Ctrl-]

indent

Ctrl-End

go to cell end

Ctrl-[

dedent

Ctrl-Down

go to cell end

Ctrl-A

select all

Ctrl-Left

go one word left

Ctrl-Z

undo

Ctrl-Right

go one word right

Ctrl-/

comment

Ctrl-M

enter command mode

Ctrl-D

delete whole line

Ctrl-Shift-F

open the command palette

Ctrl-U

undo selection

Ctrl-Shift-P

open the command palette

Insert

toggle overwrite flag

Esc

enter command mode

Ctrl-Backspace

delete word before

Ctrl-Y

redo

Ctrl-Delete

delete word after

Alt-U

redo selection

Shift-Enter

run cell, select below

Ctrl-Shift-Minus

split cell at cursor

Ctrl-Enter

run selected cells

Down

move cursor down

Alt-Enter

run cell and insert below

Up

move cursor up

Ctrl-S

Save and Checkpoint

**

Jupyter Notebook - Markdown Cells

Markdown 单元格显示可以使用 markdown 语言设置格式的文本。为了输入不应被笔记本服务器视为代码的文本,必须首先从单元格菜单中或在命令模式下使用键盘快捷键 M 将其转换为 markdown 单元格。单元格前的 In[] 提示会消失。

Markdown cell displays text which can be formatted using markdown language. In order to enter a text which should not be treated as code by Notebook server, it must be first converted as markdown cell either from cell menu or by using keyboard shortcut M while in command mode. The In[] prompt before cell disappears.

Header cell

markdown 单元格可以显示 6 种大小的标题文本,类似于 HTML 标题。通过 # 符号在 markdown 单元格中开始文本。使用与您想要标题的级别相对应的尽可能多的 # 符号。这意味着单个 # 将呈现最大的标题行,六个 # 符号呈现最小字体大小的标题。当您从单元格菜单或工具栏的运行按钮运行单元格时,将进行呈现。

A markdown cell can display header text of 6 sizes, similar to HTML headers. Start the text in markdown cell by # symbol. Use as many # symbols corresponding to level of header you want. It means single # will render biggest header line, and six # symbols renders header of smallest font size. The rendering will take place when you run the cell either from cell menu or run button of toolbar.

以下屏幕截图显示了带有三个不同级别的标题的编辑模式下的 markdown 单元格。

Following screenshot shows markdown cells in edit mode with headers of three different levels.

markdown cells three levels

当单元格运行时,输出如下 −

When cells are run, the output is as follows −

markdown cells output

请注意,Jupyter 笔记本标记语言不支持 WYSWYG 功能。只有在运行标记单元格后才会呈现格式化效果。

Note that Jupyter notebook markdown doesn’t support WYSWYG feature. The effect of formatting will be rendered only after the markdown cell is run.

Ordered Lists

若要按 HTML 的 <ol> 标签的原理呈现带序号的列表,列表中的第一项应编为 1。后续各项可以编为任意数字。运行标记单元格后,这些数字将按顺序呈现。若要显示缩进列表,请按 Tab 键,并以每个子列表中的 1 开头。

To render a numbered list as is done by <ol> tag of HTML, the First item in the list should be numbered as 1. Subsequent items may be given any number. It will be rendered serially when the markdown cell is run. To show an indented list, press tab key and start first item in each sublist with 1.

如果您为标记语言输入以下数据:

If you give the following data for markdown −

ordered lists

将显示以下列表:

It will display the following list −

ordered list output

Bullet lists

列表中的每一项都会显示一个实心圆圈,如果它以 – 符号开头,而如果列表以 * 符号开头,则会显示实心方块符号。以下示例解释了此功能 −

Each item in the list will display a solid circle if it starts with – symbol where as solid square symbol will be displayed if list starts with * symbol. The following example explains this feature −

bullet lists

呈现的降价以如下显示 −

The rendered markdown shows up as below −

bullet lists output

使用 http 或 https 开头的降价文本自动呈现超链接。若要将链接附加到文本上,请将文本放在方括号 [] 中并将其放在圆括号 () 中(可选地包括悬停文本)。以下屏幕截图对此进行了说明。

Markdown text starting with http or https automatically renders hyperlink. To attach link to text, place text in square brackets [] and link in parentheses () optionally including hovering text. Following screenshot will explain this.

including hyperlink

呈现的降价以如下显示 −

The rendered markdown appears as shown below −

hyperlink included

Bold and Italics

若要以粗体显示文本,请将其放在双下划线或两个星号之间。若要以斜体显示,请将其放在单下划线或单个星号之间。

To show a text in bold face, put it in between double underscores or two asterisks. To show in italics, put it between single underscores or single asterisks.

applying bold italics

结果以如下所示 −

The result is as shown below −

bold italics output

Images

若要在降价单元格中显示图片,请从编辑菜单中选择“插入图片”选项,然后浏览到需要的图片文件。降价单元格显示其语法如下 −

To display image in a markdown cell, choose ‘Insert image’ option from Edit menu and browse to desired image file. The markdown cell shows its syntax as follows −

logo attachment

图片将在笔记本上呈现如下所示 −

Image will be rendered on the notebook as shown below −

jupyter logo

Table

在降价单元格中,可以使用 |(管道符号)和 –(破折号)来构造表格,以标记列和行。请注意,在键入时符号不必完全对齐。它只需占据列边框和行边框的相应位置即可。笔记本将根据内容自动调整大小。表格构造如下所示 −

In a markdown cell, a table can be constructed using | (pipe symbol) and – (dash) to mark columns and rows. Note that the symbols need not be exactly aligned while typing. It should only take respective place of column borders and row border. Notebook will automatically resize according to content. A table is constructed as shown below −

table construction

输出表格将呈现如下所示 −

The output table will be rendered as shown below −

table output

Jupyter Notebook - Cell Magic Functions

在这一章中,让我们了解单元格魔术函数及其功能。

In this chapter, let us understand cell magic functions and their functionalities.

%%html

这个单元格魔术函数将代码单元格的内容渲染为 html 脚本。

This cell magic function renders contents of code cell as html script.

html script

%%js or %%javascript

使用这个单元格魔术命令,你可以在 Jupyter 笔记本单元格中嵌入 javascript 代码。

You can embed javascript code in Jupyter notebook cell with the help of this cell magic command.

javascript code
javascript code output

%%writefile

使用这个命令将代码单元格的内容写入到文件中。

Contents of code cell are written to a file using this command.

write file

Jupyter Notebook - Plotting

Jupyter 笔记本的 IPython 内核可以显示输入单元格中的代码绘图。它可以与 matplotlib 库无缝协作。 %matplotlib 魔术函数的 inline 选项可以在即使未调用绘图对象 show() 函数的情况下渲染绘图单元格。 show() 函数导致图形在不带数字的 [] 中单元格的下方显示。

IPython kernel of Jupyter notebook is able to display plots of code in input cells. It works seamlessly with matplotlib library. The inline option with the %matplotlib magic function renders the plot out cell even if show() function of plot object is not called. The show() function causes the figure to be displayed below in[] cell without out[] with number.

matplotlib library

现在,在末尾加上 plt.show() 再运行一次单元格来查看差别。

Now, add plt.show() at the end and run the cell again to see the difference.

注意 %matplotlib notebook 魔术渲染交互式绘图。

Note that the %matplotlib notebook magic renders interactive plot.

就在图形的下方,你可以找到一个切换视图、平移、缩放和下载选项的工具栏。

Just below the figure, you can find a tool bar to switch views, pan, zoom and download options.

matplotlib library toolbar

重要的是,如果你修改绘图下方的源数据,显示会动态变化,而无需绘制另一副绘图。

Importantly, if you modify the data underneath the plot, the display changes dynamically without drawing another plot.

在上面的示例中,修改单元格中 x 和 y 的数据集,再次绘制图形,上面的图形将得到动态刷新。

In the above example, change the data sets of x and y in the cell below and plot the figure again, the figure above will get dynamically refreshed.

modifying data underneath

Jupyter - Converting Notebooks

Jupyter 笔记本文件具有 .ipynb 扩展名。笔记本 app 会在网络浏览器中呈现笔记本。它可以通过使用文件菜单中下载作为选项导出到各种文件格式。Jupyter 还有 nbconvert 选项形式的命令行界面。默认情况下,nbconvert 将笔记本导出为 HTML 格式。您可以使用以下命令用于此目的 −

Jupyter notebook files have .ipynb extension. Notebook is rendered in web browser by the notebook app. It can be exported to various file formats by using download as an option in the file menu. Jupyter also has a command line interface in the form of nbconvert option. By default, nbconvert exports the notebook to HTML format. You can use the following command for tis purpose −

jupyter nbconvert mynotebook.ipynb

这会将 mynotebook.ipynb 转换为 mynotebook.html 。其他导出格式通过 --to 子句指定。

This will convert mynotebook.ipynb to the mynotebook.html. Other export format is specified with --to clause.

请注意,其他选项包括 ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides']

Note that other options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides']

HTML 包含 'basic' 和 'full' 模板。您可以按如下所示在命令行中指定 −

HTML includes 'basic' and 'full' templates. You can specify that in the command line as shown below −

jupyter nbconvert --to html --template basic mynotebook.ipynb

LaTex 是一种特别用于科学排版的文档编制格式。Jupyter 包含 'base', 'article' 和 'report' 模板。

LaTex is a document preparation format used specially in scientific typesetting. Jupyter includes 'base', 'article' and 'report' templates.

jupyter nbconvert --to latex –template report mynotebook.ipynb

要通过 latex 生成 PDF,请使用以下命令 −

To generate PDF via latex, use the following command −

jupyter nbconvert mynotebook.ipynb --to pdf

笔记本可以导出到 HTML 幻灯片放映。转换在后台使用 Reveal.js。要由 HTTP 服务器处理幻灯片,请在命令行中添加 --postserve。要生成不需要 Internet 连接的幻灯片,只需将 Reveal.js 库放在 your_talk.slides.html 所在的同一目录中。

Notebook can be exported to HTML slideshow. The conversion uses Reveal.js in the background. To serve the slides by an HTTP server, add --postserve on the command-line. To make slides that does not require an internet connection, just place the Reveal.js library in the same directory where your_talk.slides.html is located.

jupyter nbconvert myslides.ipynb --to slides --post serve

markdown 选项将笔记本转换为简单的 markdown 输出。Markdown 单元格不受影响,而代码单元格缩进了 4 个空格。

The markdown option converts notebook to simple markdown output. Markdown cells are unaffected, and code cells indented 4 spaces.

--to markdown

您可以使用 rst 选项将笔记本转换为 Basic reStructuredText 输出。它可以用作将笔记本嵌入到 Sphinx 文档中的起点。

You can use rst option to convert notebook to Basic reStructuredText output. It is useful as a starting point for embedding notebooks in Sphinx docs.

--to rst

这是从笔记本中获取 Python(或其他语言,取决于内核)脚本的最简单方法。

This is the simplest way to get a Python (or other language, depending on the kernel) script out of a notebook.

--to script

Jupyter Notebook - IPyWidgets

IPyWidgets 是一个用于 Jupyter 笔记本的 HTML 交互式小部件的 Python 库。库中的每个 UI 元素都可以响应事件并调用指定的事件处理程序函数。它们增强了 Jupyter 笔记本应用程序的交互功能。

IPyWidgets is a Python library of HTML interactive widgets for Jupyter notebook. Each UI element in the library can respond to events and invokes specified event handler functions. They enhance the interactive feature of Jupyter notebook application.

为了在笔记本中加入小部件,我们必须导入以下模块,如下图所示 −

In order to incorporate widgets in the notebook, we have to import the following module as shown below −

from ipywidgets import widgets

一些基本的 IPyWidgets 在此处解释 −

Some basic IPyWidgets are explained here −

Text input

widgets.text() 函数在笔记本中渲染小部件。它类似于 HTML 中的文本框表单元素。此小部件的对象具有 on_submit() 方法,该方法会侦听文本字段的活动并且能够调用作为参数给它的事件处理程序。

The widgets.text() function renders widgets in the notebook. It is similar to text box form element in HTML. The object of this widget has on_submit() method which listens to activity of the text field and can invoke event handler given as an argument to it.

Button

这个小组件类似于 HTML 按钮。当它被点击时,事件由 on_click() 方法注册,该方法调用点击事件处理程序。

This widget is similar to HTML button. When it is clicked, the event is registered by on_click() method which calls the click event handler.

IntSlider

一个滑块控件,显示增量整数值。还有 FloatSlider 和 IntRangeSlider(改变范围内的整数)

A slider control which displays the incrementing integer values. There is also a FloatSlider and IntRangeSlider (changing integer between a range)

Label

这个小组件对于在笔记本中显示不可编辑文本很有用。

This widget is useful to display non editable text in the notebook.

display()

这个来自 ipywidgets 模块的函数在笔记本的输入单元格中渲染小组件对象。

This function from ipywidgets module renders the widget object in notebook’s input cell.

Interact

这个函数根据给定的数据参数类型自动渲染一个控件。该函数的第一个参数是事件处理程序,第二个是传递给事件处理程序本身的一个值。

This function automatically renders a widget depending upon type of data argument given to it. First argument to this function is the event handler and second is a value passed to event handler itself.

下面的例子显示了三个标签控件、两个文本控件和一个带“添加”标题的按钮。当点击这个按钮时,两个文本输入框中的数字之和显示在最底部的标签上。

Following example shows three label widgets, two text widgets and a button with ‘add’ caption. When the button is clicked, sum of numbers in two text input fields is displayed on the lowermost label.

form creation

Jupyter QtConsole - Getting Started

在本章中,让我们了解如何开始使用 QtConsole。本章将为您概述此软件并说明其安装步骤。

In this chapter, let us understand how to get started with QtConsole. This chapter will give you an overview about this software and explains its installation steps.

Overview

Qt 控制台是一款类似于 IPython 终端的 GUI 应用程序。然而,它提供了一些在基于文本的 IPython 中无法获取的增强功能。增强功能包括:内联图形、具有语法高亮的多分行编辑、图形化调用提示等。Qt 控制台可以用任何 Jupyter 内核,缺省为 IPython 内核。

The Qt console is a GUI application similar to IPython terminal. However, it provides a number of enhancements which are not available in text based IPython terminal. The enhance features are inline figures, multi-line editing with syntax highlighting, graphical calltips, etc. The Qt console can use any Jupyter kernel, default being IPython kernel.

Installation

Jupyter QtConsole 是 Project Jupyter 的一部分。Anaconda 发行版中已经包含了 QTconsole 应用程序。若要自行安装,请使用 pip 命令,如下所示:

Jupyter QtConsole is a part of Project Jupyter. Anaconda distribution is already having QTconsole application in it. In order to install it individually, use pip command as shown below −

pip3 install qtconsole

您还可以使用 conda 命令来达到此目的:

You can also use the conda command for this purpose −

conda install qtconsole

您可以从 Anaconda 导航器启动 Jupyter 控制台。若要从命令行启动它,您应该使用以下命令,可以在 Windows 命令提示符或 Anaconda 提示符中使用:

You can start Jupyter console from Anaconda navigator. To start it from the command line, you should use the following command, either from the Windows command prompt or Anaconda prompt −

jupyter qtonsole

您将获得一个类似于 IPython 终端的终端,开头是 In[] 提示。现在您可以执行任何 Python 表达式,就像我们在 IPython 终端或 Jupyter 笔记本中执行的一样。

You get a terminal similar to IPython terminal with first In[] prompt. You can now execute any Python expression exactly like we do in IPython terminal or Jupyter notebook

jupyter qtconsole

Jupyter QtConsole - Multiline Editing

多行编辑是 IPython 终端中不可用的特性之一。为了在单一输入单元中输入多条语句,在第一行后按下 ctrl+enter 。此后,仅仅按下回车即可在同一单元中添加新行。若要停止输入新行并运行单元,再次在结尾处按下回车键。单元将运行,并且输出将显示在下一个 out[] 单元中。

Multiline editing is one of the features which is not available in IPython terminal. In order to enter more than one statements in a single input cell, press ctrl+enter after the first line. Subsequently, just pressing enter will go on adding new line in the same cell. To stop entering new lines and running cell, press enter key one more time at the end. The cell will run and output will be displayed in next out[] cell.

multiline editing

Jupyter QtConsole - Inline Graphics

QtConsole 提供的另一个重要增强功能是能够显示内联图形,尤其适用于图表。此功能适用于 Matplotlib 和其他绘图库。

Another important enhancement offered by QtConsole is the ability to display inline graphics, especially plots. The feature works well with Matplotlib as well as other plotting libraries.

lnline graphics

Jupyter QtConsole - Save to HTML

在 File 菜单中提供将 QtConsole 输出保存为 HTML 文件的此选项。你可以选择创建带有嵌入图像的文件,或者将绘图图形作为一个外部 png 文件放在一个邻接文件夹(名为 qt_files)中。

This option to save the QtConsole output as HTML file is available in File menu. You can choose to create file with inline image or the plotted figure as external png file in an adjacent folder (named as qt_files).

qtconsole output html

Jupyter QtConsole - Multiple Consoles

您可以在 Jupyter 控制台应用程序中打开多个选项卡。文件菜单中提供了三个选项来实现此目的。

You can open more than one tabs in Jupyter console application. Three options in File menu are provided for this purpose.

  1. New Tab with New kernel − You can load a new kernel with this file menu.

  2. New Tab with Existing kernel − Using this option, you can choose from additional kernels apart from IPython kernel.

  3. New Tab with Same Kernel − This creates a slave of kernel loaded on a particular tab. As a result, object initialized on master tab will be accessible in slave and vice versa.

multiple consoles

Connecting to Jupyter Notebook

有一个可供与 Jupyter notebook 一起使用的 %qtconsole 魔术命令。这将调用 QtConsole 作为 notebook 前端的从属终端。因此,可以在 notebook 和 Qtconsole 终端之间共享数据。

There is a %qtconsole magic command available for use with Jupyter notebook. This invokes the QtConsole as a slave terminal to notebook frontend. As a result, data between notebook and Qtconsole terminal can be shared.

connecting jupyter notebook

您可以看到 notebook 中的变量可在 qtconsole 窗口内访问。此外,Qtconsole 中的新变量已在 notebook 中重新使用。

You can see that the variable in notebook is accessible within qtconsole window. Also, a new variable in Qtconsole is used back in notebook.

请注意,两个输入单元格和输出单元格之间的编号是递增的。

Observe that the input and output cells are numbered incrementally between the two.

Using github and nbviewer

Sharing Jupyter notebook – Using github and nbviewer

Sharing Jupyter notebook – Using github and nbviewer

当一个 GitHub 仓库中的 Jupyter Notebook 文件带有 .ipynb 扩展名时,当它们被打开时,它们将被渲染成静态 HTML 文件。笔记本的交互特性,诸如自定义的 JavaScript 绘图,将无法在你 GitHub 中的仓库中工作。

Jupyter Notebook files with .ipynb extension in a GitHub repository will be rendered as static HTML files when they are opened. The interactive features of the notebook, such as custom JavaScript plots, will not work in your repository on GitHub.

要使用 GitHub 共享笔记本文件,请登录到 https://github.com ,创建一个公共仓库。然后使用文件上传按钮上传你的文件,如下所示:

To share notebook file using github, login to https://github.comand create a public repository. Then upload your files using upload file button as shown below −

github

这会给你一个选择来提交对仓库所做更改的机会。然后,仓库会显示如下上传的文件:

This will give you an option to commit the changes made to the repository. Then, the repository will show uploaded file as below −

updated repository

点击上传的文件在 GitHub 查看器中查看。你可以把高亮的网址分享给别人。

Click on the uploaded file to view inside github viewer. You can share the highlighted URL to others.

inside github viewer

查看笔记本文件的另一种方法是使用 Project Jupyter 的 nbviewer 工具。打开 https://nbviewer.jupyter.org/ ,把你的仓库的文件 URL 放到文本框中,如所示。按下 Go 按钮查看笔记本。

Another way to view the notebook file online is by using nbviewer utility of Project Jupyter. Open https://nbviewer.jupyter.org/ and put URL of file in your repository in the textfield as shown. Press Go button to view the notebook.

nbviewer

这两种方法都会把笔记本文件显示为静态 HTML。为了能够在笔记本中执行代码,使用 Jupyter 项目的 Binder 应用程序打开它。

Both these methods display notebook file as static html. To be able to execute code in the notebook, open it using Binder application of Jupyter project.

binder application

在 nbviewer 窗口中,你会看到 “在 Binder 中执行” 按钮。点击它,你会看到笔记本文件被打开,就像你从本地机器中笔记本服务器的本地仪表盘打开它一样。你可以执行诸如添加/编辑单元格、运行单元格等所有操作。

In the nbviewer window you will see ‘Execute on Binder’ button. Click on it and you will see the notebook file opened exactly like you open it from local dashboard of notebook server on your local machine. You can perform all actions like add/edit cells, run the cells etc.

execute on binder

JupyterLab - Overview

Project Jupyter 将 JupyterLab 描述为 Jupyter 生态系统下所有产品的下一代基于 Web 的用户界面。它使你能够以一种可扩展的方式与笔记本、编辑器和终端无缝工作。

Project Jupyter describes JupyterLab as a next generation web based user interfaces for all products under the Jupyter ecosystem. It enables you to work seamlessly with notebook, editors and terminals in an extensible manner.

下面讨论了 JupyterLab 的一些重要功能:

Some of the important features of JupyterLab are discussed below −

  1. Code Console acts as scratchpad for running code interactively. It has full support for rich output and can be linked to a notebook kernel to log notebook activity.

  2. Any text file (Markdown, Python, R, LaTeX, etc.) can be run interactively in any Jupyter kernel.

  3. Notebook cell output can be shown into its own tab, or along with the notebook, enabling simple dashboards with interactive controls backed by a kernel.

  4. Live editing of document reflects in other viewers such as editors or consoles. It is possible to have live preview of Markdown, Delimiter-separated Values, or Vega/Vega-Lite documents.

JupyterLab 可以处理许多文件格式(图像、CSV、JSON、Markdown、PDF 等)。它还以这些格式显示丰富型输出。JupyterLab 提供可自定义的键盘快捷方式,它使用许多知名文本编辑器的键映射。

JupyterLab can handle many file formats (images, CSV, JSON, Markdown, PDF etc.). It also displays rich output in these formats. JupyterLab provides customizable keyboard shortcuts uses key maps from many well-known text editors.

JupyterLab - Installation and Getting Started

在安装之前你可以在线试用 JupyterLab 的功能。访问 https://jupyter.org/try 并选择“试用 JupyterLab”选项。

You can try online the features of JupyterLab before installing. Visit https://jupyter.org/try and choose ‘try JupyterLab’ option.

jupyter lab

启动器标签显示当前可用的内核和控制台。你可以基于它们任何一个启动一个新的笔记本/终端。左列也有用于文件浏览器、运行内核、标签页和设置视图的标签页。

The launcher tab shows currently available kernels and consoles. You can start a new notebook based/terminal based on any of them. The left column is also having tabs for file browser, running kernels and tabs and settings view.

JupyterLab 通常通过 Anaconda 分发自动安装。但是,它也可以通过以下 conda 命令单独安装 −

JupyterLab is normally installed automatically with Anaconda distribution. However, it can also be installed separately by using following conda command −

conda install -c conda-forge jupyterlab

您还可以为此使用 pip 命令 −

You can also use the pip command for this purpose −

pip3 install jupyterlab

要启动 JupyterLab 应用程序,最方便的方法是通过安装的 Anaconda 导航器。

To start JupyterLab application, most convenient way is from Anaconda Navigator if it is installed.

anaconda navigator

或者从 Windows/Linux 命令终端或 Anaconda 提示符使用此命令从命令行启动它 −

Alternately start it from command line from Windows/Linux command terminal or Anaconda prompt using this command −

jupyter lab

无论哪种方式,JupyterLab 应用程序的启动画面如下所示 −

Either way, the JupyterLab application’s launch screen looks like this −

launch screen

JupyterLab - Interface

若要启动一个新的笔记本,请单击所需的内核。在以上屏幕截图中,可以看到一个内核,即 Python3 内核。单击它以启动一个 Python 笔记本。请注意,它的功能类似于我们本教程中所研究的功能。

To start a new notebook, click the desired kernel. In above screenshot, one kernel is seen that is Python3 kernel. Click it to start a Python notebook. Observe that its functionality is similar to the one we have studied in this tutorial.

start python notebook

Menu Bar

菜单栏在窗口的顶部。您可以在其中找到的缺省菜单是:

The menu bar is at the top of window. The default menus you can find in this are −

  1. File − Actions related to files and directories.

  2. Edit − Actions related to editing documents and other activities.

  3. View − Actions that alter the appearance of JupyterLab.

  4. Run − Actions for running code in different activities such as notebooks and code consoles.

  5. Kernel − Actions for managing kernels, which are separate processes for running code.

  6. Tabs − A list of the open documents and activities in the dock panel.

  7. Settings − Common settings and an advanced settings editor.

  8. Help − A list of JupyterLab and kernel help links.

左边的侧边栏显示按钮用于启动新启动器、添加文件夹、上传文件和刷新文件列表。右侧窗格是主要工作区域,其中笔记本、控制台和终端以标签视图显示。

The left sidebar shows buttons for starting a new launcher, adding a folder, uploading file and refresh file list. The right pane is the main working area where notebook, console and terminals are shown in tabbed view.

若要启动新控制台,请单击左侧边栏中的 + 符号以打开新启动器,然后单击控制台选项。控制台将在右侧窗格的新标签中打开。

To start a new console, click + symbol in the left side bar to open a new launcher and then click the console option. The console will open in new tab on the right pane.

starting new console

请注意,输入单元格位于底部,但运行后,单元格及其相应的输出单元格将显示在控制台标签的上部。

Note that the input cell is at the bottom, but when it is run, the cell and its corresponding output cell appears in upper part of console tab.

启动器还允许您打开一个文本编辑器和一个可以调用 IPython shell 的终端。

The launcher also allows you open a text editor and a terminal in which IPython shell can be invoked.

ipython shell text editor

JupyterLab - Installing R Kernel

Project Jupyter 现在支持编程环境内核。现在我们将了解如何安装 Anaconda 发行版中的 R 内核。

Project Jupyter now supports kernels of programming environments. We shall now see how to install R kernel in anaconda distribution.

在 Anaconda 提示符窗口中输入以下命令 −

In Anaconda prompt window enter following command −

conda install -c r r-essentials

现在,从启动程序选项卡中,选择 R 内核以启动新的笔记本。

Now, from the launcher tab, choose R kernel to start a new notebook.

launcher tab r kernel

以下是具有 R 内核的 Jupyter 笔记本的屏幕截图 −

The following is a screenshot of Jupyter notebook having R kernel −

jupyter notebook r kernel