NumPy 学习
numpy是python中一个科学计算有关的库
Main Object:ndarray
alias:array(以下所指的array均是指该array) 可变对象
In NumPy dimensions are called axes. The number of axes is rank(这里的rank是维数).
每个轴的编号依次是0,1,2…,以下称第0维,第1维,第2维…
对于矩阵,第0维是列,第1维是行。
注意ndarray和array的构造函数不同,ndarray的第一个参数是 shape,array的第一个参数是array_like object.
Attributes:
ndarray.ndim : rank
ndarray.shape : a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns,shape will be (n,m).
ndarray.size : the total number of elements of the array. This is equal to the product of the elements of shape.
ndarray.dtype : an object describing the type of the elements in the array.(its own:numpy.int32,numpy.int16,numpy.float64)
数据转换时可以自动向宽转换,不能自动向窄转换(more general or precise)
ndarray.itemsize : the size in bytes of each element of the array(equivalent to ndarray.dtype.itemsize)
An example
import numpy as np
a=np.arange(15).reshape(3,5)
#a=array([[0 ,1 ,2 ,3 ,4 ],
# [5 ,6 ,7 ,8 ,9 ],
# [10,11,12,13,14]])
a.shape #(3,5)
a.ndim #2
a.dtype.name #'int64'
a.itemsize #8
a.size #15
type(a) #<type 'numpy.ndarray'>
b=np.array([6,7,8]) #b=array([6,7,8])
Print Arrays
b=np.arange(12).reshape(4,3)
print(b)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]]
Array Creation
Basic
a=np.array([1,2,3,4]) #first param:a single list of numbers
b=np.array([(1.5,2,3),(4,5,6)]) #param should be sequences
c=np.array([1,3],[2,4],dtype=complex)
Function
- zero((m,n)) : creates an array full of zeros
- ones((m,n)) : creates an array full of ones
- empty((m,n)) : creates an array depending on the state of the memory
- eye(m[,n]) :返回单位阵
- diag(v) : 返回对角阵,v是对角向量可以为list,一维array等
- diag(A) : 返回矩阵的对角元素向量。
By default, the dtype of the created array is float64.
np.zeros((3,4))
np.ones((2,3,4),dtype=np.int16)
np.empty((2,3))
Sequences
arange : analogous(类似的) to range([start,]end[,step]) linspace :linear space,receives as an argument the number of elements that we want
np.arange(10,30,5) #array([10,15,20,25])
np.arange(0,2,0.3) #it accepts float arguments
np.linspace(0,1,5) #array([0,0.25,0.5,0.75,1])
Basic Operations
Operations on elements
+ - * / ** ... #矩阵与数的运算
+= *= ... #modify an existing array
< > >= <= != == ... #返回bool值矩阵
* #矩阵与矩阵对应元素的乘积
Universal Functions
NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions”(ufunc). Within NumPy, these functions operate elementwise(按元素地) on an array, producing an array as output.
sqrt,floor,power,remainder,mod,absolute,sign,
exp,exp2(2**p),log,log2,log10,cbrt(cube-root)
add,subtract,multiply,divide,reciprocal(倒数)
np.add(B,C) equivalent to B+C
Linear Algebra
详情请到官方网站
+ -
A.dot(B) #两个矩阵的乘积
np.dot(A,B) #与上式等价
@ #与上式等价
#如果A,B是两个向量,返回两个向量的内积
A.T,A.transpose() #A的转置
np.linalg.det(A) #行列式
np.linalg.inv(A) #逆
np.trace(A) #矩阵的迹
np.linalg.norm(A) #向量的2-norm,矩阵的F-norm(Frobenius)
np.linalg.solve(A,b) #解方程组Ax=b
[eig_vals,eig_vecs]=np.linalg.eig(A) #矩阵的特征值,特征向量
# the column v[:,i] is the eigenvector corresponding to the eigenvalue w[i].
np.linalg.lstsq(A,b) #计算Ax=b的最小二乘解
Unary([‘juːnərɪ],一元的) operations (methods of the ndarray class)
可以指定轴
- sum() : compute the sum of all the elements in the array.
- max(),min():最大值、最小值
- argmax(),argmin():最大值的索引,最小值的索引;多维数组返回拉直后的索引
- mean(),平均数
By specifying the axis parameter you can apply an operation along the specified axis of an array:
b = np.arange(12).reshape(3,4)
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
b.sum(axis=0) #sum of each column 对第0维元素求和
#array([12, 15, 18, 21])
b.min(axis=1) # min of each row
#array([0, 4, 8])
b.cumsum(axis=1) # cumulative sum along each row
# array([[ 0, 1, 3, 6],
# [ 4, 9, 15, 22],
# [ 8, 17, 27, 38]])
Indexing,Slicing and Iterating
One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.
Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas.
When fewer indices are provided than the number of axes, the missing indices are considered complete slices.
The dots (…) represent as many colons as needed to produce a complete indexing tuple. For example, if x is a rank 5 array (i.e., it has 5 axes),
- x[1,2,…] is equivalent to x[1,2,:,:,:],
- x[…,3] to x[:,:,:,:,3] and
- x[4,…,5,:] to x[4,:,:,5,:].
Iterating over multidimensional arrays is done with respect to the first axis.
However, if one wants to perform an operation on each element in the array, one can use the flat attribute which is an iterator over all the elements of the array.(flat是一个迭代器)
ravel [‘ræv(ə)l]v解开 ravel()返回矩阵拉直运算的结果。 拉直方法:从前到后,从高维到低维。
example
a = np.arange(10)**3
#array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
a[2] #8
a[2:5] #array([ 8, 27, 64])
a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000 新用法
a[::-1] #reversed a
for i in a:
print(i**(1/3.))
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4),dtype=int)#f是x/行,y、列的函数,(5,4)是每维的定义域,即shape
# array([[ 0, 1, 2, 3],
# [10, 11, 12, 13],
# [20, 21, 22, 23],
# [30, 31, 32, 33],
# [40, 41, 42, 43]])
b[0:5, 1] # each row in the second column of b
# array([ 1, 11, 21, 31, 41])
b[1:3, : ] # each column in the second and third row of b
# array([[10, 11, 12, 13],
# [20, 21, 22, 23]])
b[-1] # the last row. Equivalent to b[-1,:]
array([40, 41, 42, 43])
Shape Manipulation
改变array的形状
生成一维数组 ravel()方法
返回改变形状后的数组 reshape(m,n)方法
改变数组本身的形状 resize(m,n)方法
If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated.
即该维长度会自动被算出
也可以用shape属性来写入值改变数组本身形状
a=np.arange(30)
a.shape=2,-1,3 #-1 means "whatever is needed"
a.shape #(2,5,3)
矩阵的合并
- vstack(A,B)竖直方向合并
- hstack(A,B)水平方向合并
Copies and Views
In complex cases, r_ and c_ are useful for creating arrays by stacking numbers along one axis. They allow the use of range literals (”:”)
np.r_[1:4,0,4] #允许用类似range,类似列表的方式产生行向量
array([1, 2, 3, 0, 4])
No Copy at all
Simple assignments make no copy of array objects or of their data. 直接赋值返回指针
a=np.arange(12)
b=a
b is a #True
View or Shallow Copy
Different array objects can share the same data. The view method creates a new array object that looks at the same data.
切片返回视图 Slicing an array returns a view of it.
c=a.view()#c是a的视图/浅拷贝,改变c的同时改变a,反之也成立
c is a #False
c.base is a #True
s = a[ : , 1:3]
s[:] = 10
a
# array([[ 0, 10, 10, 3],
# [1234, 10, 10, 7],
# [ 8, 10, 10, 11]])
Deep Copy
The copy method makes a complete copy of the array and its data.
copy返回深拷贝
d=a.copy()
d is a #False
Fancy indexing and index tricks
Indexing with Arrays of indices
返回索引矩阵的对应元素形成的矩阵
a=np.arange(12)**2
i=np.array([1,2,3,8,5])
a[i] #array([1,1,9,64,25])
j=np.array([[3,4],[9,7]])
a[j] #array([9,16],[81,49])
参考资料
- NumPy Quickstart tutorial