《利用Python进行数据分析》学习笔记ch03(4) - Go语言中文社区

《利用Python进行数据分析》学习笔记ch03(4)


这章主要是介绍IPython,但因为我现在一直在用Jupyter,所以结果有些出入,看后续的章节是否还有一些较大的问题,这里就先将就一下。

1.IPython基础

import numpy as np
from numpy.random import randn
data = {i:randn() for i in range(7)}
data
{0: 0.8611346383812991,
 1: 0.5362350286600601,
 2: -0.307231562803592,
 3: -0.4950796767150949,
 4: -0.15818185039404367,
 5: 1.2129329945075356,
 6: -0.14162732613012588}
from numpy.random import randn
data = {i:randn() for i in range(7)}
print(data)
{0: 2.415889425442822, 1: -0.5219924948118143, 2: 0.6772666078389369, 3: 0.25290209089906857, 4: -1.0438101366342571, 5: 0.6095941975610393, 6: 0.5779498654429005}

1.2Tab键自动完成

按下Tab键,当前命名空间中任何与已输入的字符串相匹配的变量(对象、函数等)就会被找出来

an_apple = 27
an_example = 42

an 之后会显示an_apple and an_example any
也可以在任何对象后面输入一个句点以便自动完成方法和属性的输入

b=[1,2,3]

b. 之后显示b.append b.extend等
还可以应用在模块上

import datetime

datetime. 之后显示datetime.MAXYEAR等

Tab键自动完成功能不知可以用于搜索命名空间和自动完成对象或模块属性。当输入任何看上去像是文件路劲的东西时(即使是在一个Python字符串中),按下Tab键即可找出电脑文件系统中与之匹配的东西:
Tab键自动完成功能还可用于函数关键字参数。

书上是mac系统,我用的是win系统,在文件路径上有所区别(这在上一章的路径(path)输入上就有所体现了),但是尝试好几次Tab还是没有出现自动路径选择。

1.3内省

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

b?

Type: list
String form: [1, 2, 3]
Length: 3
Docstring:
list() -> new empty list
list(iterable) -> new list initialized from iterable’s items
这就叫做对象内省(object introspection)

如果该对象是一个函数或实例方法,则其docstring(如果有的话)也会被显示出来

def add_numbers(a,b):
    """Add two numbers together

    returns
    - - - - - 
    the sum:type of arguments    
    """
    return a+b
add_numbers?

Signature: add_numbers(a, b)
Docstring:
Add two numbers together

returns


the sum:type of arguments
File: c:usersadministratordocuments
Type: function

使用??还将显示出该函数的源代码(如果可能的话):

add_numbers??

Signature: add_numbers(a, b)
Source:
def add_numbers(a,b):
“”“Add two numbers together

returns
- - - - - 
the sum:type of arguments    
"""
return a+b

File: c:usersadministratordocuments
Type: function

?还有一个用法,用搜索IPython命名空间。一些字符配以通配符(*)即可显示出所有与该通配符表达式相匹配的名称

np.*load*?

np.loader
np.load
np.loads
np.loadtxt
np.pkgload

1.4%run命令

在IPython会话环境中,所有文件都可以通过%run命令当做Python程序来运行。
假设在ipython_script_test.py中存放了一段简单的脚本,
只要将文件名传给%run就可以运行了:
%run ipython_script_test.py

1.5执行剪贴板中的代码

这一部分就不再赘述,复制粘贴的问题以前就出现过了,使用IPython时,因为是逐行编译所以不能大段的复制粘贴,这里就介绍了%paste和%cpaste这两个魔术函数,因为我现在使用的是Jupyter所以就不在用IPython实践了。
本书后面会介绍Jupyter,它使我们能以一种基于浏览器的notebook格式逐段对可执行代码单元进行分析。
目前我一直是使用Jupyter,确实很方便,日后看工作需要,如果需要IPyhon这样的工具,才尝试使用%paste和%cpaste这两个魔术函数。

1.6键盘快捷键

不再赘述,因为目前就我掌握的一些快捷键已经够用。

1.7异常和跟踪

IPython默认会输出整个调用栈跟踪(traceback),其中还会附上调用栈各点附近的几行代码作为上下参考
这里就是说了IPython解释器在对于显示异常上会出现比较详细的内容,这也是便于找出并排除异常。

1.8魔术命令

IPython有一些特殊命令(被称为魔术命令(Magic Command)),他们有的为常见任务提供便利,有的则能使你能够轻松控制IPython系统的行为,魔术命令是以百分号%为前缀的命令。

魔术命令可以看作运行于IPython系统中的命令行程序。它们大都还有一些“命令行选项”,使用?即可查看其选项

%reset?

Docstring:
Resets the namespace by removing all names defined by the user, if
called without arguments, or by removing some types of objects, such
as everything currently in IPython’s In[] and Out[] containers (see
the parameters for details).
Parameters
-f : force reset without asking for confirmation.

-s : ‘Soft’ reset: Only clears your namespace, leaving history intact.
References to objects may be kept. By default (without this option),
we do a ‘hard’ reset, giving you a new session and removing all
references to objects from the current session.

in : reset input history

out : reset output history

dhist : reset directory history

array : reset only variables that are NumPy arrays
See Also
reset_selective : invoked as %reset_selective
Examples
::

In [6]: a = 1

In [7]: a
Out[7]: 1

In [8]: ‘a’ in _ip.user_ns
Out[8]: True

In [9]: %reset -f

In [1]: ‘a’ in _ip.user_ns
Out[1]: False

In [2]: %reset -f in
Flushing input history

In [3]: %reset -f dhist in
Flushing directory history
Flushing input history
Notes
Calling this magic from clients that do not implement standard input,
such as the ipython notebook interface, will reset the namespace
without confirmation.
File: c:anaconda3libsite-packagesipythoncoremagicsnamespace.py

输入%quickref或%magic即可查看所有这些特殊命令

%magic

太长了,就不显示了,当然也不是很懂。

1.9基于Qt的富GUI控制台

IPython团队开发了一个基于Qt框架,按照书上尝试多次都没有成功。

1.10matplotlib集成与pylab模式

之前也用这个创建过图形了,这里不再赘述,详细的后面章节会讲。

1.11使用命令历史

1.12搜索并重用历史

就是按上箭头,出现前几个用过的语法,在IPython有效,在Jupyter并没有成功。

1.13输入和输出变量

IPython会将输入和输出的引用保存在一些特殊变量中。

2**27
134217728
_
134217728

输入的文本被保存在名为_ix的变量中,其中x是输入的行号。每个输入变量都有一个对应的输出变量_x。

foo='bar'
foo
'bar'
_i16
"foo='bar'"
_17
'bar'

有几个魔术命令可用于控制输入和输出历史。
%hist打印全部和部分输入历史,可以选择是否带行号;
%reset用于清空interactive命名空间,并可选择是否清空输入和输出缓存;
%xdel用于从IPython系统中一处特点对象的一切引用。

1.14记录输入和输出

IPython能够记录整个控制台会话,包括输入和输出,执行%logstart即可开始记录日志。

1.15与操作系统交互

IPython的另一个特点就是它跟操作系统shell结合得非常紧密,也就是说,你可以直接在IPyhton中实现标准的Windows或UNIX命令行活动。

1.16sehll命令和别名

在IPython中,以感叹号(!)开头的命令行表示其后的所有内容需要在系统shell中执行,可以删除文件、修改目录或执行任意其他处理过程。

1.17目录书签系统

IPython有一个简单的目录书签系统,它保存常用目录的别名以实现快速跳转

%bookmark db /home/wesm/Dropbox
cd db
(bookmark:db) -> /home/wesm/Dropbox
[WinError 3] 系统找不到指定的路径。: '/home/wesm/Dropbox'
C:UsersAdministratorDocuments

2.软件开发工具

IPython提供了一些简单易用的代码运行时间及性能分析工具。

2.1交互式调试器

调试代码的最佳时机之一就是错误刚刚发生那会儿。%debug命令(在发生异常后马上输入)将会调用那个“事后”调试器,并直接跳转到引发异常的那个栈帧(stack frame)

%debug后总是卡死

当想要设置断点或对函数/脚本进行单步调试以查看各条语句的执行情况时,使用带有-d选项的%run命令。之后立即输入s(或step)才能进入脚本。

使用IPython总是莫名卡住,但是使用IPthon就没问题

调试的其他使用场景

介绍了set_trace函数,看不懂

2.2测试代码的执行时间:%time和%timeit

测试一下各个部分或函数调用或语句的执行时间,了解哪些函数占用的时间最多。

IPython专门提供了两个魔术函数(%time和%timeit)以便自动完成该过程。

#一个非常大的字符串数组
strings = ['foo','foobar','baz','qux','python','Guido Van Rossum']*100000
method1 = [x for x in strings if x.startswith('foo')]
method2 = [x for x in strings if x[:3]=='foo']
%time method1 = [x for x in strings if x.startswith('foo')]
Wall time: 429 ms
%time method2 = [x for x in strings if x[:3]=='foo']
Wall time: 315 ms

如果对相同语句多次执行%time的话,就会发现其结果是会变的。为了得到更为精确的结果,需要使用魔术函数%timeit。对于任意语句,它会自动多次执行以产生一个非常精确的平均执行时间。

%timeit [x for x in strings if x.startswith('foo')]
1 loop, best of 3: 372 ms per loop
%timeit [x for x in strings if x[:3]=='foo']
1 loop, best of 3: 286 ms per loop
x='foobar'
y='foo'
%timeit x.startswith(y)
The slowest run took 8.09 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 746 ns per loop
%timeit x[:3]==y
The slowest run took 8.02 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 677 ns per loop

2.3基本性能分析:%prun和%run -p

代码的性能分析跟代码执行时间密切相关,只不过它关注的是耗费时间的位置。
主要的Python性能分析工具是cProfile模块,cProfile在执行一个程序或代码块时,会记录各函数所耗费的时间。

cProfile一般是在命令行上使用的,它将执行整个程序然后输出各个函数的执行时间。

import numpy as np
from numpy.linalg import eigvals
def run_experiment(niter = 100):
    K = 100
    results = []
    for _ in xrange(niter):
        mat = np.random.randn(K,K)
        max_eigenvalue = np.abs(eigvals(mat)).max()
        results.append(max_eigenvalue)
    return results
some_results = run_experiment()
print ('Largest one we saw: %s' %np.max(some_results))
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-74-a79a1debc6e1> in <module>()
----> 1 some_results = run_experiment()
      2 print ('Largest one we saw: %s' %np.max(some_results))


<ipython-input-71-2291e045be9f> in run_experiment(niter)
      4     K = 100
      5     results = []
----> 6     for _ in xrange(niter):
      7         mat = np.random.randn(K,K)
      8         max_eigenvalue = np.abs(eigvals(mat)).max()


NameError: name 'xrange' is not defined

总是报错,问题好像出在xrange中。

2.4逐行分析函数性能

使用一个叫做line_profiler的小型库,其中有一个新的魔术函数%lprun,它可以对一个或多个函数进行逐行性能分析。

通常用%prun(cProfile)做“宏观的”性能分析,而用%lprun(line_profiler)做“微观的”性能分析。

这一块也同样总是报错,我想这可能是版本的差异也可能是解释器的原因。

3.IPython HTML Notebook

import matplotlib.pyplot as plt
%matplotlib inline
img = plt.imread('C:\pytest\ch03\stinkbug.png')
plt.imshow(img)
<matplotlib.image.AxesImage at 0x266b1b53ac8>

这里写图片描述

注意这里与书上的区别。

4.利用IPython提高代码开发效率的几点提示

4.1重新加载模块依赖项

使用reload函数就可以在每次执行py文件时都使用最新版的文件。
在执行之前加一句语法。
import some_lib
reload(some_lib)

4.2代码设计提示

实践出真知

保留有意义的对象和数据

扁平结构要比嵌套结构好

无惧大文件

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u013633065/article/details/75442500
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-05-07 22:32:19
  • 阅读 ( 995 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢