Python For Data Analysis -- IPython

IPython Basics

首先比一般的python shell更方便一些
比如某些数据结构的pretty-printed,比如字典
更方便的,整段代码的copy,执行

并且可以兼容部分system shell , 比如目录浏览,文件操作等

 

Tab Completion

这个比较方便,可以在下面的case下,提示和补全未输入部分

a. 当前命名空间中的名字

image

b.对象或模块的属性和函数

image

c. 文件路径

image

 

Introspection, 内省

?,在标识符前或后加上,显示出对象状况和docstring

image 

??,显示出source code

image

?,在命名空间中search

比如用tab completion,对于numpy太多属性和函数,想用通配符*去search和过滤,但tab completion是不支持的,这时候用?

image

 

The %run Command

可以直接执行一个python脚本,

In [550]: %run ipython_script_test.py

如果脚本需要使用当前shell环境中定义的变量,使用

%run -i

 

Executing Code from the Clipboard

直接把整段代码,copy过来会有问题,需要加上%paste 或 %cpaste

执行%paste,会自动读取Clipboard的内容作为代码段,并执行,

image

%cpaste,可以随意粘帖任意多的代码, 最终用ctrl-d来结束输入,并执行

 

Keyboard Shortcuts

image

 

Magic Commands

IPython中定义的一些特殊命令,一般以%开头

如果以%%表示cell模式,即多行,比如%%timeit,可以测试多行的执行时间

使用%quickref or %magic,可以看到所有magic commands的介绍

如果没有冲突的情况下,不用加%,也是可以的(这个feature可以用%automagic来开关)

image

 

Matplotlib Integration and Pylab Mode

$ ipython --pylab

 

Using the Command History

a. 搜索history
这是用的最多的,用上下键来查找,并且上下键是支持,增量的,即输入开头,再用上下键搜索
但是有时候,只记得部分命令,不一定是开头,比如像搜索包含time的history命令,用ctrl+r

b. 快速引用历史的输入输出

用的比较多的是输出,_ (one underscore) and __ (two underscores) 分别表示,前一个,前两个命令的输出
也可以用_行号,来引用特定行的输出

image

image

引用特定行的输入,是_i行号

image

还可以用exec来执行特定的行

image

c. 整个执行过程记录到log

%logstart,%logstop

 

Interacting with the Operating System

image 

 

Software Development Tools

IPython支持Debug, %debug, 或%pdb,我一般不用debug,所以ignore

 

Timing Code: %time and %timeit

time是运行一次,而timeit是运行多次求平均值

 

Basic Profiling: %prun and %run -p

python中提供cProfile来进行performance分析
而IPython提供更方便的接口,
%prun 或 %run –p
比如,
%prun -l 7 -s cumulative run_experiment()
%run -p -s cumulative cprof_example.py

都可以进行profile,找出其中比较耗时的代码

同时还通过插件支持Profiling a Function Line-by-Line

 

IPython HTML Notebook

ipython notebook --pylab=inline

用过,觉得真的挺酷
支持python,markdown,html,可以把整个session保存在json格式的文件里.ipynb
觉得这个尤其方便教学

简单的上传和分发.ipynb,大家都可以简单的交互的更改或学习

原文地址:https://www.cnblogs.com/fxjwind/p/3899751.html