python数据分析之ipython

在用python进行数据分析的时候,需要提前安装如下几个库:

Numpy:python进行科学计算的科学包

pandas:提供了能够快速便捷地处理结构化数据的大量数据结构和函数

matplotlib: 看名字和matlab有点像,matplotlib是用于绘制数据图表的python

ipython:科学计算标准工具集的组成部分,它将其他的东西都联系到了一起。可以算是一个集成开发环境,也算是一个Python shell. 它主要用与交互式数据处理和利用matplotlib对数据进行可视化处理。

Scipy: 专门解决科学计算中的各种标准问题域的包的集合。

安装完上述的包以后,我们首先来了解ipython

我们通过命令行来启动ipython

root@zhf-maple:/home/zhf/桌面# ipython

Python 2.7.14 (default, Sep 23 2017, 22:06:14) 

Type "copyright", "credits" or "license" for more information.

 

IPython 5.5.0 -- An enhanced Interactive Python.

?         -> Introduction and overview of IPython's features.

%quickref -> Quick reference.

help      -> Python's own help system.

object?   -> Details about 'object', use 'object??' for extra details.

 

In [1]: 

可以在这里输入任何的python语句,然后按回车就可以执行了。下面的这个例子使用了np.random.randn函数。numpy中有一些产生随机数的函数。其中就包括randnrand

numpy.random.randn(d0, d1, …, dn)是从标准正态分布中返回一个或多个样本值。 
numpy.random.rand(d0, d1, …, dn)的随机样本位于[0, 1)中。 

 

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

 

In [4]: data

Out[4]: 

{0: -0.26372963026186114,

 1: 0.9897522050146305,

 2: -0.317248416264267,

 3: -0.20268379526665642,

 4: 0.24959732707744903,

 5: -0.606557876097728,

 6: -1.4078448883575148,

 7: -0.2142476262321556,

 8: 0.4230008554551093,

 9: -0.011635799533308613

 

TAB自动化功能:

shell中输入表达式时,只要按下tab键,当前命令空间中任何与已输入的的字符串相匹配的变量就会被找出来。

In [9]: apple=4

 

In [10]: appl

              apple 

              apply 

不光找出了定义的apple值,还找出了内置对象apply。 还可以在任何对象后面输入一个点号然后按下tab来查找出所有的属性。

In [11]: b=[1,2,3]

 

In [12]: b.

            b.append  b.index   b.remove  

            b.count   b.insert  b.reverse 

            b.extend  b.pop     b.sort    

 

同样的也可以应用于模块中。

In [12]: import time

 

In [13]: time.

      time.accept2dyear time.daylight     time.strftime     time.tzname       

      time.altzone      time.gmtime       time.strptime     time.tzset        

      time.asctime      time.localtime    time.struct_time                    

      time.clock        time.mktime       time.time                           

      time.ctime        time.sleep        time.timezone 

 

 

内省

在变量的前面或者后面加上一个?就可以将有关该对象的一些通用信息显示出来:

In [13]: b?

Type:        list

String form: [1, 2, 3]

Length:      3

Docstring:  

list() -> new empty list

list(iterable) -> new list initialized from iterable's items

 

这个方法对于函数也是同样适用的。?显示出这段docstring, ??显示出该函数的源代码。

In [14]: def add(a,b):

    ...:     return a+b

    ...: 

 

In [15]: add?

Signature: add(a, b)

Docstring: <no docstring>

File:      /home/zhf/桌面/<ipython-input-14-ff991a776e8a>

Type:      function

 

In [16]: add??

Signature: add(a, b)

Source:   

def add(a,b):

    return a+b

File:      /home/zhf/桌面/<ipython-input-14-ff991a776e8a>

Type:      function

 

%run命令

ipython中,所有文件都可以通过%run命令当做python程序来运行。假设有test1.py文件有如下脚本

def add_function():

    a=3

    b=4

    return a+b

result=add_function()

 

In [18]: %run /home/zhf/py_prj/test1.py

 

In [19]: result

Out[19]: 7

通过%run命令就可以直接执行。如果在执行过程中发现有错误,ipython默认会输出整个调用栈跟踪traceback

 

ipython和操作系统的交互也做得比较好。下面列出调用shell命令的魔术命令及语法

!cmd:在系统shell中执行cmd

In [29]: !ls -al

总用量 28

drwxr-xr-x  2 zhf zhf 4096 12月  4 08:13 .

drwxr-xr-x 35 zhf zhf 4096 1月  15 16:48 ..

-rwxr-xr-x  1 zhf zhf 2183 11月 28 20:51 mpv.desktop

-rwxr-xr-x  1 zhf zhf  309 11月 28 22:37 Pycharm.desktop

-rwxr-xr-x  1 zhf zhf  428 11月 28 20:51 ubuntu-kylin-software-center.desktop

-rwxr-xr-x  1 zhf zhf  714 12月  4 08:13 wps-office-et.desktop

-rwxr-xr-x  1 zhf zhf  757 12月  4 08:13 wps-office-wps.desktop

%alias: 为系统shell命令定义别名

%bookmark: 使用ipython的目录书签系统。在实际使用中,想快速的跳到某个目录,可以使用书签系统。下面的例子使用py_prj作为一个书签表示的目录是/home/zhf/py_prjcd py_prj就可以跳转到/home/zhf/py_prj目录

In [38]: %bookmark py_prj /home/zhf/py_prj

In [39]: cd py_prj

/home/zhf/py_prj

In [41]: %bookmark -l

Current bookmarks:

/home/zhf -> /home/zhf/桌面

l         -> /home/zhf/py_prj

py_prj    -> /home/zhf/py_prj

使用-l的参数可以打印出所有的书签。

%cd directory: 将系统工作目录更改为directory

%pwd: 返回系统的当前工作目录

%pushd directory: 将当前目录入栈,并转向目标目录。

%popd:弹出栈顶目录,并转向该目录

%dirs:返回一个含有当前目录栈的列表

%dhist:打印目录访问历史

%env:dict形式返回系统环境变量。

 

 

软件开发工具:

ipython中集成了pdb工具,可以很方便的对代码进行调试。在ipython中使用%run -d 脚本进入调试器

调试器的命令有如下:

h(elp):显示命令行列表

c(ontinue):恢复程序的执行

q(quit):退出调试器

b(reak) number:在当前文件的number行设置断点

s(tep):单步进入函数调用

n(next):执行当前行,并进入到下一行

u(p)/d(own):在函数调用栈中向上或向下移动

a(rgs):显示当前函数的参数

debug statement:在新的递归调试器中调用statement

l(ist) statement:显示当前行,以及当前栈级别上的上下文参考代码

w(here):打印当前位置的完整栈跟踪。

In [51]: %run -d test1.py

Breakpoint 1 at /home/zhf/py_prj/test1.py:1

NOTE: Enter 'c' at the ipdb>  prompt to continue execution.

> /home/zhf/py_prj/test1.py(2)<module>()

1     1 

----> 2 def add_function():

      3     a=3

      4     b=4

      5     return a+b

 

ipdb> s

> /home/zhf/py_prj/test1.py(8)<module>()

      4     b=4

      5     return a+b

      6 

      7 

----> 8 result=add_function()

 

 

测试代码的执行时间:

python中如果要计算代码的执行时间一般都是用如下的方法:

import time

start=time()

******function******

end=time()

during=end-start

ipython中专门提供了2个魔术函数自动完成该过程。%time一次执行一个语句,然后报告执行的总体时间,

In [52]: string=['zhf','maple','zhfcmx','zhanghongfeng','chengdu','chongqing']

 

In [53]: %time method=[x for x in string if x.startswith('zhf')]

CPU times: user 4 µs, sys: 1 µs, total: 5 µs

Wall time: 5.96 µs

In [54]: %time method=[x for x in string if x.startswith('zhf')]

CPU times: user 9 µs, sys: 2 µs, total: 11 µs

Wall time: 16 µs

但是可以发现,每次对同一个过程执行相同的%time返回的结果都不一样,所以%time的结果并不是一个非常精确的结果。ipython还提供了%timeit 命令来多次执行并返回一个精确的平均执行时间

In [55]: %timeit method=[x for x in string if x.startswith('zhf')]

The slowest run took 5.50 times longer than the fastest. This could mean that an intermediate result is being cached.

1000000 loops, best of 3: 564 ns per loop

 

ipython HTML Notebook:

Notebookipthon一个很棒的功能,它把命令行交互从终端搬到了网页上,对于演示来说非常方便。首先需要安装jupyterpip install jupyter

root@zhf-maple:/home/zhf/py_prj# ipython notebook

[TerminalIPythonApp] WARNING | Subcommand `ipython notebook` is deprecated and will be removed in future versions.

[TerminalIPythonApp] WARNING | You likely want to use `jupyter notebook` in the future

[I 18:27:56.358 NotebookApp] Writing notebook server cookie secret to /run/user/1000/jupyter/notebook_cookie_secret

[C 18:27:56.372 NotebookApp] Running as root is not recommended. Use --allow-root to bypass.

这里提示不建议用root帐号登录。添加--allow-root后就开始运行了

root@zhf-maple:/home/zhf/py_prj# ipython notebook --allow-root

[TerminalIPythonApp] WARNING | Subcommand `ipython notebook` is deprecated and will be removed in future versions.

[TerminalIPythonApp] WARNING | You likely want to use `jupyter notebook` in the future

[I 18:28:09.174 NotebookApp] Serving notebooks from local directory: /home/zhf/py_prj

[I 18:28:09.174 NotebookApp] 0 active kernels

[I 18:28:09.174 NotebookApp] The Jupyter Notebook is running at:

[I 18:28:09.174 NotebookApp] http://localhost:8888/?token=d830e950b77bd0325e68bbbab4a8b1fd0f8936d8ec029b03

[I 18:28:09.174 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

[C 18:28:09.176 NotebookApp] 

    

    Copy/paste this URL into your browser when you connect for the first time,

    to login with a token:

        http://localhost:8888/?token=d830e950b77bd0325e68bbbab4a8b1fd0f8936d8ec029b03

 

浏览器会自动弹出网路界面如下,会将当前工作目录下的文件都显示出来

new下点击Python2就可以进入在线交互平台

在此可以输入交互命令,每个交互命令都是一个cell,可以在前后分别插入cell也就是命令。点击Run后即可运行

 

转载于:https://www.cnblogs.com/zhanghongfeng/p/8289369.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值