numpy的优势:运算迅速,支持多维数据
数组创建及常用函数
a = np.array([2,3,4])
b = np.array([2.0,3.0,4.0,5.0]).reshape((2,2)) #若reshape中某参数为-1,也即数组规模不变,根据其他参数自动计算
c = np.array([[1.0,2.0],[3.0,4.0]])
d = np.array([[1,2],[3,4]],dtype=complex) # 指定数据类型,int ,int32,int64,float32,float64
- 数组的常用函数
print np.arange(0,7,1,dtype=np.int16) # 0为起点,间隔为1时可缺省(引起歧义下不可缺省)
print np.ones((2,3,4),dtype=np.int16) # 2页,3行,4列,全1,指定数据类型
print np.zeros((2,3,4)) # 2页,3行,4列,全0
print np.empty((2,3)) #值取决于内存
print np.arange(0,10,2) # 起点为0,不超过10,步长为2
print np.linspace(-1,2,5) # 起点为-1,终点为2,取5个点
print np.random.randint(0,3,(2,3)) # 大于等于0,小于3,2行3列的随机整数
其他:np.clip 截断函数等
基本运算
- 元素级
a = np.array([1,2,3,4])
b = np.arange(4)
print a, b
print a-b
print a*b #逐个元素对应 不是矩阵
print a**2
print 2*np.sin(a)
print a>2
print np.exp(a) # 指数
[1 2 3 4] [0 1 2 3]
[1 1 1 1]
[ 0 2 6 12]
[ 1 4 9 16]
[ 1.68294197 1.81859485 0.28224002 -1.51360499]
[False False True True]
[ 2.71828183 7.3890561 20.08553692 54.59815003]
- 矩阵运算(二维数组)
a = np.array([[1,2],[3,4]]) # 2行2列
b = np.arange(6).reshape((2,-1)) # 2行3列
print a,b
print a.dot(b) # 2行3列
输出:
[[1 2]
[3 4]] [[0 1 2]
[3 4 5]]
[[ 6 9 12]
[12 19 26]]
- 非数组运算,调用方法
a = np.random.randint(0,5,(2,3))
print a
print a.sum(),a.sum(axis=1),a.sum(0) # axis用于指定运算轴(默认全部,可指定0或1)
print a.min(),a.max(axis=1),a.mean(axis=1) # axis = 0: 按列计算,axis = 1: 按行计算
print a.cumsum(1) # 按行计算累积和
输出:
[[2 3 3]
[0 2 1]]
11 [8 3] [2 5 4]
0 [3 2] [ 2.66666667 1. ]
[[2 5 8]
[0 2 3]]
索引
A[1,2]
A[1][2]
A[1,:]
A[1,1:2] #只有A[1][1]处的值
数组以row为默认索引 故 for row in A 按行输出
若以列为迭代可以将A转置 for column in A.T
若想要输出每一个项目(元素),则可以使用flat重构A
A.flatten() 返回一个一行的序列
for item in A.flat: 中 flat则返回一个迭代器
合并
a=np.array([1,1,1])
b=np.array([2,2,2])
np.vstack(a,b) #上下合并,合并为一个数组[[1 1 1],
[2 2 2]]
np.hstack(a,b) #左右合并,合并为一个序列[1 1 1 2 2 2]
一维数组(序列)[1 1 1] 不能通过T转置为[[1][1][1]],shape是(3,) 所以需要增加一列
故 A[:,np.newaxis].shape()为(3,1),就可以转置得到
concatenate函数其实可以把前面几个函数代替。
数组分割
等分:np.split() 不等分:np.array_split()
np.vsplit() 上下分割
np.hsplit() 左右分割
复制的关联性
= 的赋值方式会带有关联性
b =a b is a #TRUE
更改任何一个都是互相关联变化的
copy() 的赋值方式没有关联性
b=a.copy
改变任何一方不影响另一方