Hi!请登陆

快速掌握数据分析必备工具,ipython和jupyter notebook

2021-3-12 46 3/12

来源:麦叔编程

作者:麦叔

本文帮你快速掌握数据分析师必须会用的两个工具 - ipython和jupyter notebook。

既然有了Python,为什么还要ipython?麦叔不用说话,给你一张图你就明白啦。jupyter notebook又是什么鬼?

建议把本文放到收藏夹。吃灰也好过需要的时候找不到。

一、iPython

iPython是Interactive Python,它是基于Python的一个包装。它其实就是一个可以通过pip安装的包。提供了普通python之外的一些功能,其中一个功能就是可以显示图片。

iPython在数据分析师,数据科学家,人工智能科学中经常使用。

(1)安装

python -m pip install ipython

(2)使用

ipython就是Python,使用方法和使用普通的交互式Python一样,代码也一样。只不过输出显示上有一定优化。

进入ipython:

[email protected] data_analysis % ipython

Python 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53)

Type 'copyright', 'credits' or 'license' for more information

IPython 7.21.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

2.使用ipython:为了运行一下代码,请先安装numpy:

python -m pip install numpy

In [1]: a = 5

In [2]: b = "麦叔"

In [3]: import numpy as np

In [4]: data = {i:np.random.randn() for i in range(7)}

In [5]: data

Out[5]:

{0: 0.8738401705018338,

1: 0.7173530856483666,

2: 1.269301701227684,

3: -0.6322949353286054,

4: -2.3619895093818295,

5: -0.9031446928993554,

6: -0.07942775508126601}

3.问号寻求帮助:

In [4]: name = 'maishu'

In [5]: name?

Type: str

String form: maishu

Length: 6

Docstring:

str(object='') -> str

str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or

errors is specified, then the object must expose a data buffer

that will be decoded using the given encoding and error handler.

Otherwise, returns the result of object.__str__() (if defined)

or repr(object).

encoding defaults to sys.getdefaultencoding().

errors defaults to 'strict'.

4.退出

In [10]: quit()

[email protected] data_analysis %

5.画图 为了运行一下代码需要先安装matplotlib

python -m pip install matplotlib

In [1]: import numpy as np

In [2]: %matplotlib

Using matplotlib backend: MacOSX

In [3]: import matplotlib.pyplot as plt

In [4]: plt.plot(np.random.randn(50).cumsum())

Out[4]: []

二、jupyter notebook

数据科学家们觉得ipython还不够过瘾,又在ipython基础上开发了jupyter notebook:一个基于网页的写代码界面。

jupyter是基于ipython的,很多操作几乎都一样。但是它有很多独特优点:

(1)文件可以保存为ipynb的文件

(2)在线编写代码

(3)支持多人协作

(4)支持markdown格式的文档

1. 安装

python -m pip install jupyter

2. 启动

> jupyter notebook

这个命令会在本机的8888端口上运行一个网站,并自动打开浏览器:

http://localhost:8888/tree

3. 基本使用

(1)创建文件

(2)编写和运行代码

(3)保存和修改文件名

文件保存在你打开jupyter notebook的目录下:

文件的格式是ipynb

4. Tab补全

在notebook中打代码的过程中,按Tab键可以自动提示和补全,类似于Pycharm和VSCode等IDE的功能:

它可支持:

(1)自动补全变量名

(2)自动补全函数名

(3)自动补全文件名等

5. 集成matplotlib画图

6. 魔术命令

(1)运行脚本:%run

(2)打印命令输入历史:%hist

(3)运行效率:%timeit

(4)其他魔术命令

7. 快捷键

(1)停止执行:Ctrl+C

(2)其他ipython快捷键

相关推荐