python numpy flatten中的xmat.flatten.a是什么意思

python的推导式(实用)
python的推导式(实用)
[摘要:每次看大牛的代码很希奇,比方T=[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
那是甚么鬼,一个变量T为何弄得那么拥堵,看着也乏啊]
每次看大牛的代码很奇怪,比如T=[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
这是什么鬼,一个变量T为什么搞得这么拥挤,看着也累啊,后来查了一下才知道这个叫推导式。
推导式是可以从一个数据序列构建另一个新的数据序列的结构体。&
【列表推导式】
列表推导能非常简洁的构造一个新列表:只用一条简洁的表达式即可对得到的元素进行转换变形
其基本格式如下:
代码如下:[expr for value in collection ifcondition]
过滤条件可有可无,取决于实际应用,只留下表达式;相当于下面这段for循环:
result = []
for value in collection:
if condition:
result.append(expression)例1: 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
&&& names = ['bob','tom','alice','jerry','wendy','smith']
&&& [name.upper() for name in names if len(name)&3]
['alice', 'jerry', 'wendy', 'smith']例2: 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
&&& [(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]例3: 求m中3,6,9组成的列表
&&& m = [[1,2,3],
... [4,5,6],
... [7,8,9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
&&& [row[2] for row in m]
#或者用下面的方式
&&& [m[row][2] for row in (0,1,2)]
例4: 求m中斜线1,5,9组成的列表
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
&&& [m[i][i] for i in range(len(m))]
[1, 5, 9]例5: 求m,n中矩阵和元素的乘积
&&& m = [[1,2,3],
... [4,5,6],
... [7,8,9]]
&&& n = [[2,2,2],
... [3,3,3],
... [4,4,4]]
&&& [m[row][col]*n[row][col] for row in range(3) for col in range(3)]
[2, 4, 6, 12, 15, 18, 28, 32, 36]
&&& [[m[row][col]*n[row][col] for col in range(3)] for row in range(3)]
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]
&&& [[m[row][col]*n[row][col] for row in range(3)] for col in range(3)]
[[2, 12, 28], [4, 15, 32], [6, 18, 36]]例5: 讲字典中age键,按照条件赋新值
{'pay': 3000, 'job': 'dev', 'age': 42, 'name': 'bob smith'}
{'pay': 4000, 'job': 'hdw', 'age': 45, 'name': 'sue jones'}
&&& people = [bob, sue]
&&& [rec['age']+100 if rec['age'] &= 45 else rec['age'] for rec in people] # 注意for位置
[42, 145]例6,如下的列表推导式结合两个列表的元素,如果元素之间不相等的话:
&&& [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]等同于:
&&& combs = []
&&& for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]值得注意的是在上面两个方法中的&for&和&if&语句的顺序。
如果想要得到一个元组 (例如,上面例子中的&(x,&y)),必须要加上括号:
&&& vec = [-4, -2, 0, 2, 4]
&&& # create a new list with the values doubled
&&& [x*2 for x in vec]
[-8, -4, 0, 4, 8]
&&& # filter the list to exclude negative numbers
&&& [x for x in vec if x &= 0]
&&& # apply a function to all the elements
&&& [abs(x) for x in vec]
[4, 2, 0, 2, 4]
&&& # call a method on each element
&&& freshfruit = ['
banana', '
loganberry ', 'passion fruit
&&& [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
&&& # create a list of 2-tuples like (number, square)
&&& [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
&&& # the tuple must be parenthesized, otherwise an error is raised
&&& [x, x**2 for x in range(6)]
File &&stdin&&, line 1, in ?
[x, x**2 for x in range(6)]
SyntaxError: invalid syntax
&&& # flatten a list using a listcomp with two 'for'
&&& vec = [[1,2,3], [4,5,6], [7,8,9]]
&&& [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]列表推导式可使用复杂的表达式和嵌套函数:
&&& from math import pi
&&& [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
列表推导式可以嵌套。
考虑以下的 3x4 矩阵,一个列表中包含三个长度为4的列表:
&&& matrix = [
... & & [1, 2, 3, 4],
... & & [5, 6, 7, 8],
... & & [9, 10, 11, 12],
现在,如果你想交换行和列,可以用嵌套的列表推导式:
&&& [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]像前面看到的,嵌套的列表推导式是对 for 后面的内容进行求值,所以上例就等价于:
&&& transposed = []
&&& for i in range(4):
transposed.append([row[i] for row in matrix])
&&& transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]反过来说,如下也是一样的:
&&& transposed = []
&&& for i in range(4):
# the following 3 lines implement the nested listcomp
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
&&& transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]在实际中,你应该更喜欢使用内置函数组成复杂流程语句。对此种情况 zip() 函数将会做的更好:
&&& list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
【字典推导式】
字典和集合推导式是该思想的延续,语法差不多,只不过产生的是集合和字典而已。其基本格式如下:
代码如下:{ key_expr: value_expr for value in collection if condition }
例1: 用字典推导式以字符串以及其长度建字典
&&& strings = ['import','is','with','if','file','exception']
&&& d = {key: val for val,key in enumerate(strings)}
{'exception': 5, 'is': 1, 'file': 4, 'import': 0, 'with': 2, 'if': 3}
【集合推导式】
集合推导式跟列表推导式非常相似,唯一区别在于用{}代替[]。其基本格式如下:
{ expr for value in collection if condition }
例1: 用集合推导建字符串长度的集合
&&& strings = ['a','is','with','if','file','exception']
&&& {len(s) for s in strings} #有长度相同的会只留一个,这在实际上也非常有用
set([1, 2, 4, 9])
【嵌套列表推导式】
嵌套列表是指列表中嵌套列表,比如说:
&&& l = [[1,2,3],
[7,8,9]]例1: 一个由男人列表和女人列表组成的嵌套列表,取出姓名中带有两个以上字母e的姓名,组成列表
names = [['tom','billy','jefferson','andrew','wesley','steven','joe'],
['alice','jill','ana','wendy','jennifer','sherry','eva']]
用for循环实现:
for lst in names:
for name in lst:
if name.count('e') &= 2:
tmp.append(name)
['jefferson', 'wesley', 'steven', 'jennifer']
用嵌套列表实现:
&&& names = [['tom','billy','jefferson','andrew','wesley','steven','joe'],
['alice','jill','ana','wendy','jennifer','sherry','eva']]
&&& [name for lst in names for name in lst if name.count('e')&=2] #注意遍历顺序,这是实现的关键
['jefferson', 'wesley', 'steven', 'jennifer']
感谢关注 Ithao123Python频道,是专门为互联网人打造的学习交流平台,全面满足互联网人工作与学习需求,更多互联网资讯尽在 IThao123!
Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。
Hadoop是一个由Apache基金会所开发的分布式系统基础架构。
用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。
Hadoop实现了一个分布式文件系统(Hadoop Distributed File System),简称HDFS。HDFS有高容错性的特点,并且设计用来部署在低廉的(low-cost)硬件上;而且它提供高吞吐量(high throughput)来访问应用程序的数据,适合那些有着超大数据集(large data set)的应用程序。HDFS放宽了(relax)POSIX的要求,可以以流的形式访问(streaming access)文件系统中的数据。
Hadoop的框架最核心的设计就是:HDFS和MapReduce。HDFS为海量的数据提供了存储,则MapReduce为海量的数据提供了计算。
随着国内互联网的发展,产品经理岗位需求大幅增加,在国内,从事产品工作的大部分岗位为产品经理,其实现实中,很多从事产品工作的岗位是不能称为产品经理,主要原因是对产品经理的职责不明确,那产品经理的职责有哪些,本专题将详细介绍产品经理的主要职责
PHP(外文名:PHP: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,利于学习,使用广泛,主要适用于Web开发领域。PHP 独特的语法混合了C、Java、Perl以及PHP自创的语法。它可以比CGI或者Perl更快速地执行动态网页。用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTML(标准通用标记语言下的一个应用)文档中去执行,执行效率比完全生成HTML标记的CGI要高许多;PHP还可以执行编译后代码,编译可以达到加密和优化代码运行,使代码运行更快。
IThao123周刊在Matplotlib极等值线图-python,matplotlib,制图graphing-CodeGo.net
在Matplotlib极等值线图
我有一组数据,我想产生极性共Matplotlib的等高线图。
我的数据是这样的:theta-角度值的一维数组radius-一维数值数组value-这是我想要的profile值的一维数组
这些都是正确对齐所有的一维数组-例如:
theta radius value
也就是说,所有的值被重复足以使三个变量这个'表'中的每一行定义了一个点。
我怎样才能创建这些值极性等高线图?我已经想过转换和θ值x和y的值,并做在笛卡尔坐标,但profile函数似乎需要二维数组,我也不太明白为什么。
任何想法?
本文地址 :CodeGo.net/322940/
-------------------------------------------------------------------------------------------------------------------------
1. Matplotlib的contour()函数需要的数据被安排成分和为每个网格点的值对应的网格的二维网格。如果您的数据自然是排列在网格中,你可以转换R,西塔,以X,Ycontour(r*np.cos(theta), r*np.sin(theta), values)让你的cabal。
如果您的数据是不自然的网格化,你应该遵循反建议griddata()插值到网格数据。
下面的脚本显示了两个例子。
import pylab as plt
from matplotlib.mlab import griddata
import numpy as np
# data on a grid
r = np.linspace(0, 1, 100)
t = np.linspace(0, 2*np.pi, 100)
r, t = np.meshgrid(r, t)
z = (t-np.pi)**2 + 10*(r-0.5)**2
plt.subplot(121)
plt.contour(r*np.cos(t), r*np.sin(t), z)
# ungrid data, then re-grid it
r = r.flatten()
t = t.flatten()
x = r*np.cos(t)
y = r*np.sin(t)
z = z.flatten()
xgrid = np.linspace(x.min(), x.max(), 100)
ygrid = np.linspace(y.min(), y.max(), 100)
xgrid, ygrid = np.meshgrid(xgrid, ygrid)
zgrid = griddata(x,y,z, xgrid, ygrid)
plt.subplot(122)
plt.contour(xgrid, ygrid, zgrid)
plt.show()
我不知道是否有可能直接做一个极等高线图,但如果你转换成直角坐标你griddata发挥你的一维数组转换为2D。
本文标题 :在Matplotlib极等值线图
本文地址 :CodeGo.net/322940/
Copyright (C) 2014 CodeGo.net2013年10月 其他开发语言大版内专家分月排行榜第二2012年2月 其他开发语言大版内专家分月排行榜第二
2013年11月 其他开发语言大版内专家分月排行榜第三2012年4月 其他开发语言大版内专家分月排行榜第三2011年6月 其他开发语言大版内专家分月排行榜第三
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。博客访问: 1308067
博文数量: 180
博客积分: 3184
博客等级: 中校
技术积分: 3736
注册时间:
APP发帖 享双倍积分
IT168企业级官微
微信号:IT168qiye
系统架构师大会
微信号:SACC2013
分类: Python/Ruby
迭代多维数组是就第一个轴而言的:
>>> for row in b:
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
然而,如果一个人想对每个数组中元素进行运算,我们可以使用flat属性,该属性是数组元素的一个迭代器:
>>> for element in b.flat:
print element,
0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43
更多[], …, newaxis, ndenumerate, indices, index exp 参考
更改数组的形状
一个数组的形状由它每个轴上的元素个数给出:
>>> a = floor(10*random.random((3,4)))
array([[ 7.,
>>> a.shape
一个数组的形状可以被多种命令修改:
>>> a.ravel() # flatten the array
array([ 7.,
>>> a.shape = (6, 2)
>>> a.transpose()
array([[ 7.,
由ravel()展平的数组元素的顺序通常是“C风格”的,就是说,最右边的索引变化得最快,所以元素a[0,0]之后是a[0,1]。如果数组被改变形状(reshape)成其它形状,数组仍然是“C风格”的。NumPy通常创建一个以这个顺序保存数据的数组,所以ravel()将总是不需要复制它的参数。但是如果数组是通过切片其它数组或有不同寻常的选项时,它可能需要被复制。函数reshape()和ravel()还可以被同过一些可选参数构建成FORTRAN风格的数组,即最左边的索引变化最快。
reshape函数改变参数形状并返回它,而resize函数改变数组自身。
array([[ 7.,
>>> a.resize((2,6))
array([[ 7.,
如果在改变形状操作中一个维度被给做-1,其维度将自动被计算
更多 shape, reshape, resize, ravel 参考
组合(stack)不同的数组
几种方法可以沿不同轴将数组堆叠在一起:
>>> a = floor(10*random.random((2,2)))
array([[ 1.,
>>> b = floor(10*random.random((2,2)))
array([[ 3.,
>>> vstack((a,b))
array([[ 1.,
>>> hstack((a,b))
array([[ 1.,
函数column_stack以列将一维数组合成二维数组,它等同与vstack对一维数组。
>>> column_stack((a,b))
# With 2D arrays
array([[ 1.,
>>> a=array([4.,2.])
>>> b=array([2.,8.])
>>> a[:,newaxis]
# This allows to have a 2D columns vector
array([[ 4.],
>>> column_stack((a[:,newaxis],b[:,newaxis]))
array([[ 4.,
>>> vstack((a[:,newaxis],b[:,newaxis])) # The behavior of vstack is different
array([[ 4.],
row_stack函数,另一方面,将一维数组以行组合成二维数组。
对那些维度比二维更高的数组,hstack沿着第二个轴组合,vstack沿着第一个轴组合,concatenate允许可选参数给出组合时沿着的轴。
在复杂情况下,r_[]和c_[]对创建沿着一个方向组合的数很有用,它们允许范围符号(“:”):
>>> r_[1:4,0,4]
array([1, 2, 3, 0, 4])
当使用数组作为参数时,r_和c_的默认行为和vstack和hstack很像,但是允许可选的参数给出组合所沿着的轴的代号。
更多函数hstack , vstack, column_stack , row_stack , concatenate , c_ , r_ 参见.
将一个数组分割(split)成几个小数组
使用hsplit你能将数组沿着它的水平轴分割,或者指定返回相同形状数组的个数,或者指定在哪些列后发生分割:
>>> a = floor(10*random.random((2,12)))
array([[ 8.,
>>> hsplit(a,3)
# Split a into 3
[array([[ 8.,
9.]]), array([[ 0.,
5.]]), array([[ 0.,
>>> hsplit(a,(3,4))
# Split a after the third and the fourth column
[array([[ 8.,
2.]]), array([[ 9.],
[ 9.]]), array([[ 0.,
vsplit沿着纵向的轴分割,array split允许指定沿哪个轴分割。
复制和视图
当运算和处理数组时,它们的数据有时被拷贝到新的数组有时不是。这通常是新手的困惑之源。这有三种情况:
完全不拷贝
简单的赋值不拷贝数组对象或它们的数据。
>>> a = arange(12)
# no new object is created
>>> b is a
# a and b are two names for the same ndarray object
>>> b.shape = 3,4
# changes the shape of a
>>> a.shape
Python 传递不定对象作为参考,所以函数调用不拷贝数组。
>>> def f(x):
print id(x)
# id is a unique identifier of an object
视图(view)和浅复制
不同的数组对象分享同一个数据。视图方法创造一个新的数组对象指向同一数据。
>>> c = a.view()
>>> c is a
>>> c.base is a
# c is a view of the data owned by a
>>> c.flags.owndata
>>> c.shape = 2,6
# a's shape doesn't change
>>> a.shape
>>> c[0,4] = 1234
# a's data changes
切片数组返回它的一个视图:
>>> s = a[ : , 1:3]
# spac could also be written "s = a[:,1:3]"
>>> s[:] = 10
# s[:] is a view of s. Note the difference between s=10 and s[:]=10
这个复制方法完全复制数组和它的数据。
>>> d = a.copy()
# a new array object with new data is created
>>> d is a
>>> d.base is a
# d doesn't share anything with a
>>> d[0,0] = 9999
函数和方法(method)总览
这是个NumPy函数和方法分类排列目录。这些名字链接到,你可以看到这些函数起作用。
arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r , zeros, zeros_like
astype, atleast 1d, atleast 2d, atleast 3d, mat
array split, column stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, item, newaxis, ravel, repeat, reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack
all, any, nonzero, where
argmax, argmin, argsort, max, min, ptp, searchsorted, sort
choose, compress, cumprod, cumsum, inner, fill, imag, prod, put, putmask, real, sum
cov, mean, std, var
基本线性代数
cross, dot, outer, svd, vdot
广播法则(rule)
广播法则能使通用函数有意义地处理不具有相同形状的输入。
广播第一法则是,如果所有的输入数组维度不都相同,一个“1”将被重复地添加在维度较小的数组上直至所有的数组拥有一样的维度。
广播第二法则确定长度为1的数组沿着特殊的方向表现地好像它有沿着那个方向最大形状的大小。对数组来说,沿着那个维度的数组元素的值理应相同。
应用广播法则之后,所有数组的大小必须匹配。更多细节可以从这个找到。
花哨的索引和索引技巧
NumPy比普通Python序列提供更多的索引功能。除了索引整数和切片,正如我们之前看到的,数组可以被整数数组和布尔数组索引。
通过数组索引
>>> a = arange(12)**2
# the first 12 square numbers
>>> i = array( [ 1,1,3,8,5 ] )
# an array of indices
# the elements of a at the positions i
array([ 1,
9, 64, 25])
>>> j = array( [ [ 3, 4], [ 9, 7 ] ] )
# a bidimensional array of indices
# the same shape as j
array([[ 9, 16],
[81, 49]])
当被索引数组a是多维的时,每一个唯一的索引数列指向a的第一维[^5]。以下示例通过将图片标签用调色版转换成色彩图像展示了这种行为。
>>> palette = array( [ [0,0,0],
[255,0,0],
[0,255,0],
[0,0,255],
[255,255,255] ] )
>>> image = array( [ [ 0, 1, 2, 0 ],
# each value corresponds to a color in the palette
[ 0, 3, 4, 0 ]
>>> palette[image]
# the (2,4,3) color image
[255, 255, 255],
我们也可以给出不不止一维的索引,每一维的索引数组必须有相同的形状。
>>> a = arange(12).reshape(3,4)
array([[ 0,
9, 10, 11]])
>>> i = array( [ [0,1],
# indices for the first dim of a
>>> j = array( [ [2,1],
# indices for the second dim
>>> a[i,j]
# i and j must have equal shape
array([[ 2,
[ 7, 11]])
>>> a[i,2]
array([[ 2,
[ 6, 10]])
>>> a[:,j]
# i.e., a[ : , j]
array([[[ 2,
[11, 11]]])
自然,我们可以把i和j放到序列中(比如说列表)然后通过list索引。
>>> l = [i,j]
# equivalent to a[i,j]
array([[ 2,
[ 7, 11]])
然而,我们不能把i和j放在一个数组中,因为这个数组将被解释成索引a的第一维。
>>> s = array( [i,j] )
# not what we want
---------------------------------------------------------------------------
IndexError
Traceback (most recent call last)
----> 1 a[s]
IndexError: index (3) out of range (0<=index>>
>>> a[tuple(s)]
# same as a[i,j]
array([[ 2,
[ 7, 11]])
另一个常用的数组索引用法是搜索时间序列最大值。
>>> time = linspace(20, 145, 5)
# time scale
>>> data = sin(arange(20)).reshape(5,4)
# 4 time-dependent series
array([[ 0.
[-0.7568025 , -0., -0.2794155 ,
0.6569866 ],
0., -0., -0.],
[-0., -0., -0.,
>>> ind = data.argmax(axis=0)
# index of the maxima for each series
array([2, 0, 3, 1])
>>> time_max = time[ ind]
# times corresponding to the maxima
>>> data_max = data[ind, xrange(data.shape[1])] # => data[ind[0],0], data[ind[1],1]...
>>> time_max
>>> data_max
array([ 0.,
0.6569866 ])
>>> all(data_max == data.max(axis=0))
你也可以使用数组索引作为目标来赋值:
>>> a = arange(5)
array([0, 1, 2, 3, 4])
>>> a[[1,3,4]] = 0
array([0, 0, 2, 0, 0])
然而,当一个索引列表包含重复时,赋值被多次完成,保留最后的值:
>>> a = arange(5)
>>> a[[0,0,2]]=[1,2,3]
array([2, 1, 3, 3, 4])
这足够合理,但是小心如果你想用Python的+=结构,可能结果并非你所期望:
>>> a = arange(5)
>>> a[[0,0,2]]+=1
array([1, 1, 3, 3, 4])
即使0在索引列表中出现两次,索引为0的元素仅仅增加一次。这是因为Python要求a+=1和a=a+1等同。
通过布尔数组索引
当我们使用整数数组索引数组时,我们提供一个索引列表去选择。通过布尔数组索引的方法是不同的我们显式地选择数组中我们想要和不想要的元素。
我们能想到的使用布尔数组的索引最自然方式就是使用和原数组一样形状的布尔数组。
>>> a = arange(12).reshape(3,4)
>>> b = a > 4
# b is a boolean with a's shape
array([[False, False, False, False],
[False, True, True, True],
[True, True, True, True]], dtype=bool)
# 1d array with the selected elements
array([ 5,
9, 10, 11])
这个属性在赋值时非常有用:
>>> a[b] = 0
# All elements of 'a' higher than 4 become 0
array([[0, 1, 2, 3],
[4, 0, 0, 0],
[0, 0, 0, 0]])
你可以参考看看如何使用布尔索引来生成曼德博集合的图像。
第二种通过布尔来索引的方法更近似于整数索引;对数组的每个维度我们给一个一维布尔数组来选择我们想要的切片。
>>> a = arange(12).reshape(3,4)
>>> b1 = array([False,True,True])
# first dim selection
>>> b2 = array([True,False,True,False])
# second dim selection
>>> a[b1,:]
# selecting rows
array([[ 4,
9, 10, 11]])
# same thing
array([[ 4,
9, 10, 11]])
>>> a[:,b2]
# selecting columns
array([[ 0,
[ 8, 10]])
>>> a[b1,b2]
# a weird thing to do
array([ 4, 10])
注意一维数组的长度必须和你想要切片的维度或轴的长度一致,在之前的例子中,b1是一个秩为1长度为三的数组(a的行数),b2(长度为4)与a的第二秩(列)相一致。
ix_函数可以为了获得的结果而用来结合不同向量。例如,如果你想要用所有向量a、b和c元素组成的三元组来计算a+b*c:
>>> a = array([2,3,4,5])
>>> b = array([8,5,4])
>>> c = array([5,4,6,8,3])
>>> ax,bx,cx = ix_(a,b,c)
array([[[2]],
array([[[8],
array([[[5, 4, 6, 8, 3]]])
>>> ax.shape, bx.shape, cx.shape
((4, 1, 1), (1, 3, 1), (1, 1, 5))
>>> result = ax+bx*cx
>>> result
array([[[42, 34, 50, 66, 26],
[27, 22, 32, 42, 17],
[22, 18, 26, 34, 14]],
[[43, 35, 51, 67, 27],
[28, 23, 33, 43, 18],
[23, 19, 27, 35, 15]],
[[44, 36, 52, 68, 28],
[29, 24, 34, 44, 19],
[24, 20, 28, 36, 16]],
[[45, 37, 53, 69, 29],
[30, 25, 35, 45, 20],
[25, 21, 29, 37, 17]]])
>>> result[3,2,4]
>>> a[3]+b[2]*c[4]
你也可以实行如下简化:
def ufunc_reduce(ufct, *vectors):
vs = ix_(*vectors)
r = ufct.identity
for v in vs:
r = ufct(r,v)
然后这样使用它:
>>> ufunc_reduce(add,a,b,c)
array([[[15, 14, 16, 18, 13],
[12, 11, 13, 15, 10],
[11, 10, 12, 14,
[[16, 15, 17, 19, 14],
[13, 12, 14, 16, 11],
[12, 11, 13, 15, 10]],
[[17, 16, 18, 20, 15],
[14, 13, 15, 17, 12],
[13, 12, 14, 16, 11]],
[[18, 17, 19, 21, 16],
[15, 14, 16, 18, 13],
[14, 13, 15, 17, 12]]])
这个reduce与ufunc.reduce(比如说add.reduce)相比的优势在于它利用了广播法则,避免了创建一个输出大小乘以向量个数的参数数组。
用字符串索引
继续前进,基本线性代数包含在这里。
简单数组运算
参考numpy文件夹中的linalg.py获得更多信息
>>> from numpy import *
>>> from numpy.linalg import *
>>> a = array([[1.0, 2.0], [3.0, 4.0]])
>>> print a
>>> a.transpose()
array([[ 1.,
>>> inv(a)
array([[-2. ,
[ 1.5, -0.5]])
>>> u = eye(2) # unit 2x2 "eye" represents "I"
array([[ 1.,
>>> j = array([[0.0, -1.0], [1.0, 0.0]])
>>> dot (j, j) # matrix product
array([[-1.,
[ 0., -1.]])
>>> trace(u)
>>> y = array([[5.], [7.]])
>>> solve(a, y)
array([[-3.],
>>> eig(j)
(array([ 0.+1.j,
array([[ 0..j,
Parameters:
square matrix
The eigenvalues, each repeated according to its multiplicity.
The normalized (unit "length") eigenvectors, such that the
column ``v[:,i]`` is the eigenvector corresponding to the
eigenvalue ``w[i]`` .
这是一个关于矩阵类的简短介绍。
>>> A = matrix('1.0 2.0; 3.0 4.0')
>>> type(A)
# file where class is defined
# transpose
>>> X = matrix('5.0 7.0')
>>> Y = X.T
>>> print A*Y
# matrix multiplication
>>> print A.I
[ 1.5 -0.5]]
>>> solve(A, Y)
# solving linear equation
matrix([[-3.],
索引:比较矩阵和二维数组
注意NumPy中数组和矩阵有些重要的区别。NumPy提供了两个基本的对象:一个N维数组对象和一个通用函数对象。其它对象都是建构在它们之上的。特别的,矩阵是继承自NumPy数组对象的二维数组对象。对数组和矩阵,索引都必须包含合适的一个或多个这些组合:整数标量、省略号(ellipses)、整数列表;布尔值,整数或布尔值构成的元组,和一个一维整数或布尔值数组。矩阵可以被用作矩阵的索引,但是通常需要数组、列表或者其它形式来完成这个任务。
像平常在Python中一样,索引是从0开始的。传统上我们用矩形的行和列表示一个二维数组或矩阵,其中沿着0轴的方向被穿过的称作行,沿着1轴的方向被穿过的是列。
让我们创建数组和矩阵用来切片:
>>> A = arange(12)
array([ 0,
9, 10, 11])
>>> A.shape = (3,4)
>>> M = mat(A.copy())
>>> print type(A),"
>>> print A
>>> print M
现在,让我们简单的切几片。基本的切片使用切片对象或整数。例如,A[:]和M[:]的求值将表现得和Python索引很相似。然而要注意很重要的一点就是NumPy切片数组不创建数据的副本;切片提供统一数据的视图。
>>> print A[:]; print A[:].shape
>>> print M[:]; print M[:].shape
现在有些和Python索引不同的了:你可以同时使用逗号分割索引来沿着多个轴索引。
>>> print A[:,1]; print A[:,1].shape
>>> print M[:,1]; print M[:,1].shape
注意最后两个结果的不同。对二维数组使用一个冒号产生一个一维数组,然而矩阵产生了一个二维矩阵。例如,一个M[2,:]切片产生了一个形状为(1,4)的矩阵,相比之下,一个数组的切片总是产生一个最低可能维度的数组。例如,如果C是一个三维数组,C[...,1]产生一个二维的数组而C[1,:,1]产生一个一维数组。从这时开始,如果相应的矩阵切片结果是相同的话,我们将只展示数组切片的结果。
假如我们想要一个数组的第一列和第三列,一种方法是使用列表切片:
>>> A[:,[1,3]]
array([[ 1,
[ 9, 11]])
稍微复杂点的方法是使用take()方法(method):
>>> A[:,].take([1,3],axis=1)
array([[ 1,
[ 9, 11]])
如果我们想跳过第一行,我们可以这样:
>>> A[1:,].take([1,3],axis=1)
array([[ 5,
[ 9, 11]])
或者我们仅仅使用A[1:,[1,3]]。还有一种方法是通过矩阵向量积(叉积)。
>>> A[ix_((1,2),(1,3))]
array([[ 5,
[ 9, 11]])
为了读者的方便,在次写下之前的矩阵:
>>> A[ix_((1,2),(1,3))]
array([[ 5,
[ 9, 11]])
现在让我们做些更复杂的。比如说我们想要保留第一行大于1的列。一种方法是创建布尔索引:
>>> A[0,:]>1
array([False, False, True, True], dtype=bool)
>>> A[:,A[0,:]>1]
array([[ 2,
[10, 11]])
就是我们想要的!但是索引矩阵没这么方便。
>>> M[0,:]>1
matrix([[False, False, True, True]], dtype=bool)
>>> M[:,M[0,:]>1]
matrix([[2, 3]])
这个过程的问题是用“矩阵切片”来切片产生一个矩阵,但是矩阵有个方便的A属性,它的值是数组呈现的。所以我们仅仅做以下替代:
>>> M[:,M.A[0,:]>1]
matrix([[ 2,
[10, 11]])
如果我们想要在矩阵两个方向有条件地切片,我们必须稍微调整策略,代之以:
>>> A[A[:,0]>2,A[0,:]>1]
array([ 6, 11])
>>> M[M.A[:,0]>2,M.A[0,:]>1]
matrix([[ 6, 11]])
我们需要使用向量积ix_:
>>> A[ix_(A[:,0]>2,A[0,:]>1)]
array([[ 6,
[10, 11]])
>>> M[ix_(M.A[:,0]>2,M.A[0,:]>1)]
matrix([[ 6,
[10, 11]])
技巧和提示
下面我们给出简短和有用的提示。
“自动”改变形状
更改数组的维度,你可以省略一个尺寸,它将被自动推导出来。
>>> a = arange(30)
>>> a.shape = 2,-1,3
# -1 means "whatever is needed"
>>> a.shape
array([[[ 0,
[ 9, 10, 11],
[12, 13, 14]],
[[15, 16, 17],
[18, 19, 20],
[21, 22, 23],
[24, 25, 26],
[27, 28, 29]]])
向量组合(stacking)
我们如何用两个相同尺寸的行向量列表构建一个二维数组?在MATLAB中这非常简单:如果x和y是两个相同长度的向量,你仅仅需要做m=[x;y]。在NumPy中这个过程通过函数column_stack、dstack、hstack和vstack来完成,取决于你想要在那个维度上组合。例如:
x = arange(0,10,2)
# x=([0,2,4,6,8])
y = arange(5)
# y=([0,1,2,3,4])
m = vstack([x,y])
# m=([[0,2,4,6,8],
[0,1,2,3,4]])
xy = hstack([x,y])
# xy =([0,2,4,6,8,0,1,2,3,4])
二维以上这些函数背后的逻辑会很奇怪。
参考并且在这里添加你的新发现: )
直方图(histogram)
NumPy中histogram函数应用到一个数组返回一对变量:直方图数组和箱式向量。注意:matplotlib也有一个用来建立直方图的函数(叫作hist,正如matlab中一样)与NumPy中的不同。主要的差别是pylab.hist自动绘制直方图,而numpy.histogram仅仅产生数据。
import numpy
import pylab
# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
mu, sigma = 2, 0.5
v = numpy.random.normal(mu,sigma,10000)
# Plot a normalized histogram with 50 bins
pylab.hist(v, bins=50, normed=1)
# matplotlib version (plot)
pylab.show()
# Compute the histogram with numpy and then plot it
(n, bins) = numpy.histogram(v, bins=50, normed=True)
# NumPy version (no plot)
pylab.plot(.5*(bins[1:]+bins[:-1]), n)
pylab.show()
阅读(62760) | 评论(0) | 转发(10) |
相关热门文章
给主人留下些什么吧!~~
请登录后评论。}

我要回帖

更多关于 python flatten 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信