Skip to content

Commit eeefd09

Browse files
committed
IPython 及 Jupyter notebook
1 parent 7522955 commit eeefd09

File tree

1 file changed

+346
-0
lines changed

1 file changed

+346
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,346 @@
1+
## 💬 IPython 及 Jupyter notebook
2+
3+
### 安装
4+
5+
+ IPython 的安装
6+
7+
```python
8+
pip install ipython
9+
```
10+
11+
+ Jupyter 的安装
12+
13+
```python
14+
pip install jupyter
15+
```
16+
17+
### 基本使用
18+
19+
+ IPython 的基本使用——启动
20+
21+
```bash
22+
# 终端中
23+
$ ipython
24+
d:\python3.9.0\lib\site-packages\IPython\core\interactiveshell.py:936: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
25+
warn("Attempting to work in a virtualenv. If you encounter problems, please "
26+
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
27+
Type 'copyright', 'credits' or 'license' for more information
28+
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
29+
30+
In [1]: a = 10
31+
32+
In [2]: a
33+
Out[2]: 10
34+
```
35+
36+
+ IPython 的基本使用——退出
37+
38+
```bash
39+
# 终端中
40+
...
41+
In [1]: exit
42+
```
43+
44+
+ Jupyter 的基本使用——启动
45+
46+
```bash
47+
# 终端中
48+
$ jupyter notebook
49+
...
50+
51+
# 通过地址 http://localhost:8888/ 来访问
52+
# Jupyter notebook 可以使用 IPython 命令
53+
```
54+
55+
+ Jupyter 的基本使用——安装第三方包
56+
57+
```python
58+
# ipython 命令行中
59+
In [1]: ! pip install xxx
60+
61+
# 如:! pip install matplotlib
62+
```
63+
64+
+ Jupyter 的基本使用——退出
65+
66+
```bash
67+
# 终端中
68+
69+
快捷键 'ctrl + C' 退出
70+
```
71+
72+
### IPython 基础
73+
74+
> 可单独作用于终端或 Jupyter notebook 中
75+
76+
+ Tab 补全
77+
78+
*变量名*
79+
80+
```python
81+
In [1]: an_apple = 27
82+
83+
In [2]: an_example = 42
84+
85+
In [3]: an<Tab>
86+
an_apple an_example any
87+
```
88+
89+
*方法、属性*
90+
91+
```python
92+
In [1]: b = [1, 2, 3]
93+
94+
In [2]: b.<Tab>
95+
b.append b.count b.insert b.reverse
96+
b.clear b.extend b.pop b.sort
97+
b.copy b.index b.remove
98+
```
99+
100+
*模块*
101+
102+
```python
103+
In [1]: import datetime
104+
105+
In [2]: datatime.<Tab>
106+
datetime.date datetime.MAXYEAR datetime.timedelta
107+
datetime.datetime datetime.MINYEAR datetime.timezone
108+
datetime.datetime_CAPI datetime.time datetime.tzinfo
109+
```
110+
111+
*路径*
112+
113+
```python
114+
In [1]: datasets/movielens/<Tab>
115+
datasets/movielens/movies,dat datasets/movielens/README
116+
datasets/movielens/ratings.dat datasets/movielens/users.dat
117+
118+
In [2]: path = 'datasets/movielens/<Tab>
119+
datasets/movielens/movies,dat datasets/movielens/README
120+
datasets/movielens/ratings.dat datasets/movielens/users.dat
121+
```
122+
123+
*关键字参数*
124+
125+
```python
126+
In [1]: def func_with_keywords(abra=1, abbra=2, abbbra=3):
127+
return abra, abbra, abbbra
128+
129+
In [2]: func_with_keywords(ab<Tab>)
130+
abbbra= abbra= abra= abs
131+
```
132+
133+
+ 内省
134+
135+
在一个变量名的前后使用问号(?)可以显示一些关于该对象的概要信息,这就是对象内省:
136+
137+
```python
138+
In [1]: b = [1, 2, 3]
139+
140+
In [2]: b?
141+
Type: list
142+
String form: [1, 2, 3]
143+
Length: 3
144+
Docstring:
145+
Built-in mutable sequence.
146+
147+
If no argument is given, the constructor creates a new empty list.
148+
The argument must be an iterable if specified.
149+
```
150+
151+
如果对象是一个函数或实例方法,则文档字符串会显示出来:
152+
153+
```python
154+
In [1]: def add_numbers(a, b):
155+
"""
156+
Add two numbers together
157+
158+
Returns
159+
-------
160+
the_sum : type of arguments
161+
"""
162+
return a + b
163+
164+
# 使用 ? 来显示文档字符串
165+
In [2]: add_numbers?
166+
Signature: add_numbers(a, b)
167+
Docstring:
168+
Add two numbers together
169+
170+
Returns
171+
-------
172+
the_sum : type of arguments
173+
File: f:\2a.python数据分析\code\<ipython-input-15-5b0474888b43>
174+
Type: function
175+
176+
# 使用 ?? 来显示函数的源代码
177+
In [3]: add_numbers??
178+
Signature: add_numbers(a, b)
179+
Source:
180+
def add_numbers(a, b):
181+
"""
182+
Add two numbers together
183+
184+
Returns
185+
-------
186+
the_sum : type of arguments
187+
"""
188+
return a + b
189+
File: f:\2a.python数据分析\code\<ipython-input-18-0e543d60c645>
190+
Type: function
191+
```
192+
193+
问号(?)可以结合星号(*)作为通配符匹配字符
194+
195+
```python
196+
In [1]: import datetime as dt
197+
198+
In [2]: dt.*time*?
199+
dt.datetime
200+
dt.datetime_CAPI
201+
dt.time
202+
dt.timedelta
203+
dt.timezone
204+
```
205+
206+
+ %run 命令
207+
208+
如果已有脚本文件 *ipython_script_test.py*
209+
210+
```python
211+
def f(x, y, z):
212+
return (x + y) / z
213+
214+
a = 5
215+
b = 6
216+
c = 7.5
217+
218+
219+
result = f(a, b, c)
220+
```
221+
222+
则可以使用 %run 命令来运行,且运行后文件中定义的所有变量、函数均可任意使用:
223+
224+
> 如果想使用 IPython 命名空间中已有的变量,则使用 **%run -i** 命令
225+
226+
```python
227+
In [1]: %run ipython_script_test.py
228+
229+
In [2]: c
230+
Out[2]: 7.5
231+
232+
In [3]: result
233+
Out[3]: 1.4666666666666666
234+
235+
In [4]: f(1, 1, 2)
236+
Out[4]: 1.0
237+
```
238+
239+
如果想把脚本导入一个代码单元,使用 %load 命令:
240+
241+
```python
242+
In [1]: %load ipython_script_test.py
243+
# %load ipython_script_test.py
244+
def f(x, y, z):
245+
return (x + y) / z
246+
247+
a = 5
248+
b = 6
249+
c = 7.5
250+
251+
252+
result = f(a, b, c)
253+
```
254+
255+
+ 魔术命令
256+
257+
IPython 的特殊命令(没有内建到 Python 自身中去)被称为“魔术”命令,这些命令被设计来简化常见任务。魔术命令呃前缀符号是百分号 %,如查看当前路径:
258+
259+
```python
260+
In [1]: %pwd
261+
Out[1]: 'F:\\2a.Python数据分析\\code'
262+
```
263+
264+
一些魔术命令可以赋值给 Python 变量:
265+
266+
```python
267+
In [1]: a = %pwd
268+
269+
In [2]: a
270+
Out[2]: 'F:\\2a.Python数据分析\\code'
271+
```
272+
273+
如果魔术命令与当前命名空间变量不冲突,则可不加 %,这种特性被称为 *自动魔术*,可使用 `%automagic` 进行启用或禁用:
274+
275+
```python
276+
In [1]: pwd
277+
Out[1]: 'F:\\2a.Python数据分析\\code'
278+
279+
In [2]: %automagic
280+
Automagic is OFF, % prefix IS needed for line magics.
281+
282+
In [3]: pwd
283+
---------------------------------------------------------------------------
284+
NameError Traceback (most recent call last)
285+
F:\2a.Python数据分析\code\ipython_script_test.py in <module>
286+
----> 1 pwd
287+
288+
NameError: name 'pwd' is not defined
289+
```
290+
291+
IPython 常用魔术命令:
292+
293+
|命令|描述|
294+
|:--|:---|
295+
|%quickref|显示 IPython 快速参考卡|
296+
|%magic|显示所有可用魔术命令的详细文档|
297+
|%debug|从最后发生报错的底部进入交互式调试器|
298+
|%hist|打印命令输入(也可以打印输出)历史|
299+
|%pdb|出现任意报错后自动进入调试器|
300+
|%pwd|显示当前路径|
301+
|%reset|删除交互式命名空间中所有的变量/名称|
302+
|%page OBJECT|通过分页器更美观地打印显示一个对象|
303+
|%run script.py|在 IPython 中运行一个 Python 脚本|
304+
|%prun statement|使用 CProfile 执行语句,并报告输出|
305+
|%time statement|报告单个语句的执行时间|
306+
|%timeit statement|多次运行单个语句计算平均执行时间;在估算代码最短执行时间时有用|
307+
|%who, %who_ls, %whos|根据不同级别的信息/详细程度,展示交互命名空间中定义的变量|
308+
|%xdel variable|在 IPython 内部删除一个变量,消除相关的引用|
309+
310+
+ matplotlib 集成
311+
312+
IPython 能在分析计算领域流行的原因之一,就是它和数据可视化、用户界面库(如 matplotlib)的良好集成。
313+
314+
注意,使用 matplotlib,要更换 numpy 版本:
315+
316+
```bash
317+
# 终端中
318+
pip install numpy==1.19.3
319+
```
320+
321+
要在 Jupyter 网页外显示图(后台),使用魔术命令 %matplotlib:
322+
323+
```python
324+
In [1]: %matplotlib
325+
Using matplotlib backend: TkAgg
326+
327+
In [2]: import matplotlib.pyplot as plt
328+
329+
In [3]: import numpy as np
330+
331+
In [4]: plt.plot(np.random.randn(50).cumsum())
332+
[<matplotlib.lines.Line2D at 0x219ce8ab700>]
333+
```
334+
335+
要在 Jupyter 网页内显示图,使用魔术命令 %matplotlib inline:
336+
337+
```python
338+
In [1]: %matplotlib inline
339+
340+
In [2]: import matplotlib.pyplot as plt
341+
342+
In [3]: import numpy as np
343+
344+
In [4]: plt.plot(np.random.randn(50).cumsum())
345+
[<matplotlib.lines.Line2D at 0x219ce615550>]
346+
```

0 commit comments

Comments
 (0)