一.索引机制、切片和迭代方法
索引 、切片操作类似于MATLAB,但是python的索引从0开始
以下各编程均在已导入numpy库下进行
1.索引
a = np.arange(2,10)
a[0]
输出 2
2.索引
a = np.arange(1,12,2).reshape(2,3)
a[0,0]
输出 1
3.切片,即提取某几行几列
a = np.arange(1,12,2).reshape(2,3)
a[0,0:2]
输出
array([1, 3])
4.迭代遍历
a = np.arange(1,12,2).reshape(2,3)
for i in a:
print(i)
输出
[1 3 5] [ 7 9 11]5.对每行或者每列做同样操作的函数,apply_along_axis(action,axis=0/1,arr=A),接受三个参数,第一个是聚合函数,如取均值,第二个是对行1还是对列0操作,第三个是需要操作的矩阵
a = np.arange(1,12,2).reshape(2,3)
np.apply_along_axis(np.mean,axis=1,arr=a)
输出 array([ 3., 9.])
6.筛选出数组中符合条件的项
a = np.arange(1,12,2).reshape(2,3)
a[a > 5] #与MATLAB及其相似
输出 array([ 7, 9, 11])
二.形状变换
1.reshape函数前面已经介绍,这里不再赘述
2.ravel函数把n维变为1维
a = np.arange(1,12,2).reshape(2,3)
a.ravel()
输出
array([ 1, 3, 5, 7, 9, 11])
3.交换矩阵的行列
a = np.arange(1,12,2).reshape(2,3)
a.transpose()
输出
array([[ 1, 7], [ 3, 9], [ 5, 11]])
三.数组操作
本文中的编程均在导入numpy库下进行
1.连接数组(不如MATLAB方便,哈哈)
(1)vstack((A,B))垂直拼接
(2)hstack((A,B))水平拼接
a = np.ones((2,3))
b = np.zeros((2,3))
c = np.vstack((a,b))
d = np.hstack((a,b))
输出
[[1. 1. 1.] [1. 1. 1.] [0. 0. 0.] [0. 0. 0.]] [[1. 1. 1. 0. 0. 0.] [1. 1. 1. 0. 0. 0.]]
2.数组切分
(1) 切分与上面对应的有vsplit(A,2),调用函数仅需一个括号
(2) 水平切分hsplit(A,2)
c = np.arange(1,17).reshape(4,4)
[C1,C2] = np.hsplit(c,2)
[C3,C4] = np.vsplit(c,2)
输出
C1[[ 1 2] [ 5 6] [ 9 10] [13 14]] C2[[ 3 4] [ 7 8] [11 12] [15 16]] C3[[1 2 3 4] [5 6 7 8]] C4[[ 9 10 11 12] [13 14 15 16]]