Python之numpy进阶版(一)
本文需要有numpy的基础知识储备
一.广播法则
广播法则能使通用函数有意义地处理不具有相同形状的输入。
- 广播第一法则:如果所有的输入数组维度不都相同,一个“1”将被重复地添加在维度较小的数组上直至所有的数组拥有一样的维度。
- 广播第二法则:确定长度为1的数组沿着特殊的方向表现地好像它有沿着那个方向最大形状的大小。对数组来说,沿着那个维度的数组元素的值理应相同。
应用广播法则之后,所有数组的大小必须匹配。
二.花哨的索引和索引技巧
Numpy比普通Python序列提供更多的索引功能。除了索引整数和切片,正如我们之前看到的,数组可以被整数数组和布尔数组索引。
(一) 通过数组索引
1、处理一维array
◆ 一维显示
from numpy import *
a = arange(12)*2 # the first 12 multiply numbers
i = array( [ 0,1,3,8,5 ] ) # an array of indices
print(a) #输出原数组
print(a[i])
运行结果
◆ 二维显示
j = array( [ [ 3, 4], [ 9, 7 ] ] ) # a bidimensional array of indices
print(a[j]) # the same shape as j
运行结果
◆ 多维显示
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 ] ] )
print(palette[image])
运行结果
2、处理多维array
◆ 情形1
from numpy import *
a = arange(12).reshape(3,4)
print(a)
i = array( [ [0,1], # indices for the first dim of a
[1,2] ] )
j = array( [ [2,1], # indices for the second dim
[3,3] ] )
print(a[i,2])
运行结果
解释说明 (自行理解)
对于a[i,2]情况,依次输出
第一行:(0,2)(1,2)
第二行: (1,2) (2,2)
◆ 情形2
print(a)
print(a[i,j]) # i and j must have equal shape
运行结果
解释说明 (自行理解)
对于a[i,j]情况,依次输出
第一行:(0,2)(1,1)
第二行: (1,3) (2,3)
◆ 情形3
print(a)
print(a[:,j])
运行结果
解释说明(自行理解)
a为3*4所以a[:,j]是一个三维数组(一个二维数组组成的一维数组)
第一个元素:第一行:(0,2)(0,1)
第二行:(0,3)(0,3)
第二个元素:第一行:(1,2)(1,1)
第二行:(1,3)(1,3)
第三个元素:第一行:(2,2)(2,1)
第二行:(2,3)(2,3)
3、搜索时间序列最大值
◆ 情形1
from numpy import *
time = linspace(20, 145, 5) # time scale
print(time)
运行结果
◆ 情形2
data = sin(arange(20)).reshape(5,4) # 4 time-dependent series
print(data)
运行结果
◆ 情形3
incl = data.argmax(axis=0) # index of the maxima for each column
print(incl)
inrw = data.argmax(axis=1) # index of the maxima for each row
print(inrw)
运行结果
4、作为目标来赋值
◆ 情形1
from numpy import *
a = arange(5)
print(a)
a[[1,3,4]] = 0
print(a)
运行结果
注:当一个索引列表包含重复时,赋值被多次完成,保留最后的值
注:如果你想用Python的+=结构,可能结果并非你所期望
a = arange(5)
a[[0,0,2]]+=1
print(a)
运行结果
解释说明
即使0在索引列表中出现两次,索引为0的元素仅仅增加一次。这是因为Python要求a+=1和a=a+1等同。
(二) 通过布尔数组索引
当我们使用整数数组索引数组时,我们提供一个索引列表去选择。通过布尔数组索引的方法是不同的我们显式地选择数组中我们想要和不想要的元素。
我们能想到的使用布尔数组的索引最自然方式就是使用和原数组一样形状的布尔数组。
1、通过布尔数组所有选择想要和不想要的元素
◆ 情形一
from numpy import *
a = arange(12).reshape(3,4)
b = a > 4
print(b) # b is a boolean with a's shape
print(a[b])
运行结果
◆ 情形2
a[b]=0
print(a)
运行结果
2、通过布尔数组切片
◆ 情形1
a = arange(12).reshape(3,4)
b1 = array([False,True,True]) # first dim selection
b2 = array([True,False,True,False]) # second dim selection
print(a[b1,:]) # selecting rows
print(a[b1])
print(a[:,b2]) # selecting columns
注:a[b1,:]与a[b1]相同
运行结果
注:一维数组的长度必须和你想要切片的维度或轴的长度一致,在之前的例子中,b1是一个秩为1长度为三的数组(a的行数),b2(长度为4)与a的第二秩(列)相一致。
结论:自学自用,希望可以喝大家积极沟通交流,如有错误还请指正,不喜勿喷