数组(ndarry)是数据基本结构(列表、元组、字典、集合)的升级形式,同时也是pandas中主要数据类型DataFrame和Series的基础。
与入门系列一的学习逻辑相同,本节从数组创建、数组属性、数组索引与切片、数组转置与轴转换、数组运算、数组排序、线性代数计算、高级数组操作等几个维度进行讲解。
目录
7.1 矩阵和向量积(Matrix and vector products)
7.4 范数和其他数字(Norms and other numbers)
7.5 解方程和逆矩阵( Solving equations and inverting matrices)
一、 数组(ndarray)创建
数组是学习pd.DataFrame和pd.Series的基础。先回答几个问题:
* 什么是数组?
数组是数据呈线性排列的一种数据结构,数组的数据按顺序存储在内存的连续空间内。
* 数组和矩阵有何区别?
数组是一种数据存储结构;矩阵是一种线性代数中的算子,具有特定的运算规则。因此,数组和矩阵计算规则不同。
在python中,数组具有特有的模块,通过import numpy as np引用。
1.1 通过np.array与np.asarray生成数组
np.array 与 np.asarray 均是将输入数据转换为ndarray,唯一不同的是,当输入数据是数组时,np.array会将数据进行复制,np.asarray则不会复制;当输入数据是其他格式时,两个函数完全相同。
>> data1=[[1,2,3],[4,5,6]]
>> arr1=np.array(data1)
>> arr2=np.asarray(data1)
>> data1[1][1]=10 # 在输入数据转换完成后,修改输入数据
>> print('arr1:',arr1,'\n','arr2:',arr2) # data修改,arr1和arr2均没有变化,均是对原数据进行了复制
[out]:arr1: [[1 2 3]
[4 5 6]]
arr2: [[1 2 3]
[4 5 6]]
>> arr3=np.ones((3,3))
>> arr4=np.array(arr3)
>> arr5=np.asarray(arr3)
>> arr3[1]=2 # 在输入数据转换完成后,修改输入数据
>> print('arr4:',arr4,'\n','arr5:',arr5) # arr3修改,arr4和arr5输出不同,由于asarray是直接转换,所以arr3的变化直接影响了arr5
[out]:arr4: [[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
arr5: [[1. 1. 1.]
[2. 2. 2.]
[1. 1. 1.]]
1.2 通过函数创建特定类型的数组
函数 | 函数说明 | 举例 |
np.arange([start,] stop[, step,], dtype=None) | 生成给定区间和间隔的数组 | np.arange(start=1,stop=5,step=2) array([1, 3]) |
np.ones(shape, dtype=None, order='C') | 生成全1数组,shape参数以元组形式输入 | np.ones((2,2)) array([[1., 1.],[1., 1.]]) |
np.zeros(shape, dtype=float, order='C') | 生成全0数组,shape参数以元组形式输入 | 同上 |
np.empty(shape, dtype=float, order='C') | 生成空数组 | 同上 |
np.full(shape, fill_value, dtype=None, order='C') | 生成由fill_value填充的全值数组 | 同上 |
np.eye(N, M=None, k=0, dtype=<class 'float'>, order='C') | 生成N×N的单位矩阵(对角线为1,其余为0) | 同上 |
二、 数组属性
示例数组 arr1:array([[1, 2, 3],[4, 5, 6]])
属性 | 方法 |
维数 | arr1.ndim [out]:2 |
尺寸 | arr1.shape [out]:(2, 3) |
数据类型 | arr1.dtype [out]:dtype('int32') 可用astype改变数据类型 |
三、 数组索引与切片
3.1 索引和切片的区别
* 索引(Indexing)
像大多数编程语言一样,Python的索引从0开始(长度为N的序列,索引序号从0到N-1),通过索引可获得索引对应的单个元素。如下图对负索引的示例:
* 切片(Slicing)
切片运算从序列类型对象中选取一系列元素,得到新的对象。以列表为例演示如下图所示的切片操作。
3.2 NumPy 数组索引
分类 | 操作 | 说明 |
一维数组 | arr = np.array([1, 2, 3, 4]) arr[0] [out]:1 | 采用array[索引序号]的形式 |
二维数组 | arr = np.array([[1,2,3,4,5], [6,7,8,9,10]]) arr[1,2] [out]:8 | 采用array[行索引序号,列索引序号]的形式 |
arr[1][2] [out]:8 | 采用array[行索引序号][列索引序号]的形式,表示先取出第2行,即[6,7,8,9,10],再从该行取出第3个元素,即元素8 | |
三维数组 | arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) arr[0,1,2] [out]:6 | 采用array[数组序号,行号、列号]的形式,表示先取出第1个数组[[1, 2, 3], [4, 5, 6]] ,再取出该数组第2行第3列的元素6 |
arr[0][1][2] | 原理同二维数组,先取出第1个数组,再取出第2行,再取出第3个元素 |
3.3 NumPy 数组切片
3.3.1 基本索引/切片
数组切片范式为:[start:end:step],其中start默认为0,可省略;step默认为1,可省略;end默认为len(arr),可省略
分类 | 说明 | 示例 |
一维数组 | 切法1:切左右闭合的一段区间,格式为[start:end] | arr=np.array([1, 2, 3, 4, 5, 6, 7]) arr[1:5] [out]:array([2, 3, 4, 5]) |
切法2:从某元素开始切片至尾部,格式为:[start:] | arr[4:] [out]:array([5, 6, 7]) | |
切法3:从数组开始元素切片至某元素,格式为:[:end] | arr[:4] [out]:array([1, 2, 3, 4]) | |
切法4:负裁切,格式为:[:-n],n为元素的负向排序序号 | arr[:-2] [out]:array([1, 2, 3, 4, 5]) | |
切法5:指定切片步长step 格式为:[start:end:step] 或[::step] | arr[::2] [out]:array([1, 3, 5, 7]) arr[1:5:2] [out]: array([2, 4]) | |
二维数组 | 二维数组的索引格式为[行索引,列索引],其中行索引和列索引的格式同一维数组 | arr2=np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) arr2[0,1:3] [out]:array([2, 3]) arr2[0,1:] [out]:array([2, 3, 4, 5]) arr2[0,:3] [out]:array([1, 2, 3]) arr2[0,::2] [out]:array([1, 3, 5]) arr2[0,0] [out]:1 |
可以看出,基本索引可以实现连续或者是具有固定间隔地取出数组元素,即规则化的索引/切片。
3.3.2 花式索引
花式索引擅长一些不规则的索引,这些不规则的索引使用其它的索引方式可能也可以实现,但是相比于花式索引实现会比较复杂。如下面的例子:
取出数组的第1行、第3行和第4行:
>> import numpy as np
>> arr=np.arange(15).reshape(5,3)
>> arr
[out]:array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])
使用基本索引方式,需要使用连接函数实现,如下:
>> a1=arr[0:3:2,:]
>> a2=arr[3,:]
>> arr1=np.row_stack((a1,a2))
>> arr1
[out]:array([[ 0, 1, 2],
[ 6, 7, 8],
[ 9, 10, 11]])
使用花式索引方式,如下:
>> arr2=arr[[0,2,3]]
>> arr2
[out]:array([[ 0, 1, 2],
[ 6, 7, 8],
[ 9, 10, 11]])
那么,什么是花式索引呢?![初探Numpy中的花式索引](https://www.kuxai.com/post/173)
花式索引(Fancy indexing)是指利用整数数组进行索引,这里的整数数组可以是Numpy数组,也可以是Python中列表、元组等可迭代类型。而基本索引输入的是数字。
花式索引的原理是:花式索引根据索引整型数组的值作为目标数组的某个轴的下标来取值。如下所示:
>> arr=np.arange(32).reshape((8,4))
>> arr
[out]:array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]])
分类 | 说明 | 示例 |
整数数组为一维时 | 情形1:只有一个整数数组 | arr[[0,2,5]] [out]:array([[ 0, 1, 2, 3],[ 8, 9, 10, 11], [20, 21, 22, 23]]) |
情形2:输入两个整数数组 | arr[[0,0],[0,3]] [out]:array([0, 3]) 下标在第一个数组中选择0,在第二个数组中选择0,等同于arr[0,0]和arr[0,3] | |
整数数组为二维时 | 输入的两个二维数组的shape要保持一致 | rows = np.array([[0,0],[3,3],[6,6]]) cols= np.array([[0,2],[0,2],[0,2]]) arr[rows,cols] [out]:array([[ 0, 2],[12, 14],[24, 26]]) 原理同上,并将取出的元素摆放在相应位置 |
花式索引与基本索引相结合 | 如arr[花式索引,基本索引] | arr[1:3,[0,3]] [out]:array([[4,7],[ 8, 11]]) arr[...,[0,3]] [out]:array([[ 0, 3], [ 4, 7], [ 8, 11],[12, 15], [16, 19], [20, 23],[24, 27],[28, 31]]) |
3.3.3 花式索引的等价函数
* np.take 切片、取数
np.take(a, indices, axis=None, out=None, mode='raise')
Take elements from an array along an axis.
>> arr=np.random.randint(1,20,(2,4))
>> arr
[out]:array([[16, 11, 11, 4],
[ 3, 5, 6, 15]])
>> indices=[2,0,2,1]
# 方法1:使用花式索引取数
>> arr[:,indices]
[out]:array([[11, 16, 11, 11],
[ 6, 3, 6, 5]])
# 方法2:使用take函数取数
>> arr.take(indices,axis=1)
[out]:array([[11, 16, 11, 11],
[ 6, 3, 6, 5]])
* np.put 赋值
np.put(a, ind, v, mode='raise') Replaces specified elements of an array with given values. v : array_like,Values to place in `a` at target indices.
>> a = np.arange(5)
>> np.put(a, [0, 2], [-44, -55])
>> a
[out]:array([-44, 1, -55, 3, 4])
3.3.4 布尔索引
布尔索引通过布尔运算(如:比较运算符)来获取符合指定条件的元素的数组。
>> arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
>> arr[arr>5]
[out]:array([ 6, 7, 8, 9, 10, 11, 12])
>> arr[~(arr<=5)] # 通过~取反
[out]:array([ 6, 7, 8, 9, 10, 11, 12])
四、数组转置与轴转换
数组与矩阵一样,可以进行转置。常见可采用两种转置方法:
4.1 使用arr.T转置
>> arr=np.arange(12).reshape(3,4)
>> arr.T
[out]:array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
4.2 使用函数np.transpose转置
>> np.transpose(arr)
[out]:array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
对于高维数组,其转置可采用np.transpose(arr,(轴序号)),具体原理参见文章[Numpy中transpose()函数的可视化理解](https://zhuanlan.zhihu.com/p/61203757)
五、 数组运算
5.1 算术运算
5.1.1 同shape数组间的算术运算
与矩阵的性质相同,同shape数组间的数学计算,都会直接在“元素”上进行运算:
>> arr1=np.arange(6).reshape(2,3)
>> arr2=np.arange(6,12).reshape(2,3)
>> arr1+arr2
[out]:array([[ 6, 8, 10],
[12, 14, 16]])
>> arr1*arr2
[out]:array([[ 0, 7, 16],
[27, 40, 55]])
>> arr1*2
[out]:array([[ 0, 2, 4],
[ 6, 8, 10]])
5.1.2 矩阵内积计算np.dot()
>> np.dot(arr1,arr2.T)
[out]:array([[ 23, 32],
[ 86, 122]])
5.1.3 同shape数组间的布尔运算
>> arr1>arr2
[out]:array([[False, False, False],
[False, False, False]])
5.1.4 不同shape数组间的算术运算
广播原则,具体略。
5.2 函数运算
5.2.1 通用函数:执行元素级运算
5.2.1.1 一元通用函数
一元通用函数接收一个数组作为变量,并在数组元素上进行计算,结果返回数组。
函数 | 说明 |
np.abs,np.fabs | 计算整点数、浮点数或复数的绝对值 |
np.sqrt | 计算平方根 square root |
np.square | 计算平方值 |
np.exp | 计算指数值 exponent |
np.log,np.log10,np.log2,np.log1P | 计算lnx,log10(x)、log2(x)、log(1+x) |
np.sign | 标记各元素正负号,1(正数)、0(零)、-1(复数) |
np.ceil | 计算大于等于元素值的最小整数 |
np.floor | 计算小于等于元素值的最大整数 |
np.rint | 四舍五入取整 roundint |
np.modf | 将数组元素的整数和小数分别以两个数组返回 |
np.isnan | 返回数组元素是否为nan的布尔型数组 |
np.isfinite,np.isinf | 返回数组元素是否为finite(有限)\infinite(无限)的布尔型数组 |
np.cos,np.cosh,np.sin,np.sinh,np.tan,np.tanh | 计算三角函数 |
np.arccos,np.arccosh,np.arcsin, np.arcsinh,np.arctan,np.arctanh | 计算反三角函数 |
np.logical_not | 逻辑非 |
5.2.1.2 二元通用函数
二元函数接收两个数组(同shape数组或者可广播的数组)作为变量,并在数组元素上进行计算,结果返回数组。
函数 | 说明 |
np.add,np.subtract, np.multiply,np.divide,np.floor_divide | 数组求和、数组相差、 数组相乘、数组相除、数组相除取整 |
np.power | 数组求幂 |
np.maximum,np.fmax; np.minimumnp.fmin | 最大值和最小值计算,fmax和fmin可忽略nan |
np.mod | 求复数的模 |
np.copysign | 将arr2的元素符号逐元素复制给arr1 |
np.greater(大于),np.greater_equal(大于等于),np.less(小于),np.less_equal(小于等于),np.equal(等于),np.not_equal(不等于) | 对arr1和arr2进行元素比较运算,返回布尔数组 |
np.logical_and,np.logical_or,np.logical_xor | 执行arr1与arr2的逻辑计算,依次为:逻辑与、逻辑或、逻辑异或 |
5.2.1.3 二元函数的ufunc方法
数组的一元通用函数可以实现对单个数组元素的简单算术计算;数组的二元函数可以实现两个数组间的元素级计算;单个数组的较为复杂的数学计算可以使用二元函数的内置ufunc方法实现,以减少循环的应用。这些方法只有对两个输入、一个输出的ufunc函数有效,其他的ufunc对象调用这些方法时会抛出ValueError异常。
生成数组为:arr1:array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
方法 | 说明 | 示例 |
np.ufunc.reduce(a,axis) | 将运算符ufunc插入到沿axis轴的所有元素之间 | 计算各列元素的和 np.add.reduce(arr1,axis=0) [out]:array([12, 15, 18, 21]) |
np.ufunc.accumulate(a,axis) | 与reduce()类似,但在进行逐步计算的过程中,会将中间结果保存下来 | np.multiply.accumulate(arr1) [out]:array([[ 0, 1, 2, 3], [ 0, 5, 12, 21], [ 0, 45, 120, 231]], dtype=int32) |
np.ufunc.reduceat(a,indices,axis) | 相当于局部reduce计算,其实就是一个对数据各切片进行聚合的groupby运算。 它接受一组用于指示如何对值进行拆分和聚合的“面元边界” | np.add.reduceat(arr1,[0,2],axis=1) [out]:array([[ 1, 5],[ 9, 13],[17, 21]], dtype=int32) 在axis=1轴向上,分别在arr1[0:2],arr1[2:]上约简 |
np.ufunc.outer(A,B) | 对数组A和数组B中的元素依次计算,返回r[i,j] = ufunc(A[i], B[j]), 生成结果维数为A.dim+B.dim,尺寸为A.shape+B.shape | np.multiply.outer([1, 2, 3], [4, 5, 6]) [out]:array([[ 4, 5, 6], [ 8, 10, 12],[12, 15, 18]]) |
5.2.2 numpy内建函数
5.2.2.1 常用统计描述函数
统计描述函数可以在ndarray指定轴向上进行运算,得出统计结果值,如np.sum(a, axis=None, dtype=None, out=None)
类别 | 说明 |
总和 | np.sum |
平均数 | np.mean |
中位数 | np.median |
最大值、最小值 | np.max、np.min |
最大、最小值索引 | np.argmax、np.argmin |
频次 | np.size |
方差 | np.var |
标准差 | np.std |
乘积 | np.prod |
累加 | np.cumsum |
累乘 | np.cumprod |
分位值 | np.quantile |
5.2.2.2 条件函数np.where
np.where(condition,x,y) 条件为True时,返回x,否则返回y。等价于[(xv if c else yv) for xv,yv,c in zip(x,y,c)]。举例如下:
>> xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
>> yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
>> cond = np.array([True, False, True, True, False])
>> [(x if c else y) for x, c, y in zip(xarr,cond,yarr)]
[out]:[1.1, 2.2, 1.3, 1.4, 2.5]
>> np.where(cond,xarr,yarr)
[out]:array([1.1, 2.2, 1.3, 1.4, 2.5])
5.2.2.3 布尔数组运算函数
方法 | 函数 |
计算True值的个数 | (arr3>3).sum() [out]:8 |
判断是否有True值 | np.any(arr3>3) [out]:True |
判断是否都为True值 | np.all(arr3>3) [out]:False |
5.2.2.4 数组集合运算函数
适用于一维数组的集合运算。
函数/方法 | 说明 |
np.unique(arr) | 数组集合化,返回唯一值 |
np.intersect1d(arr1,arr2) | 计算交集 |
np.union1d(arr1,arr2) | 计算并集 |
np.in1d(arr1,arr2) | 返回arr1包含于arr2的布尔型数组 |
np.setdiff1d(arr1,arr2) | 求集合差,即元素在arr1中但不在arr2中 |
np.setxor1d(arr1,arr2) | 求对称差,即存在于一个数组中但不同时存在于两个数组中的元素 |
六、数组排序
6.1 C和Fortran顺序
NumPy允许你更为灵活地控制数据在内存中的布局。默认情况下,NumPy数组是按行优先顺序创建的。在空间方面,这就意味着,对于一个二维数组,每行中的数据项是被存放在相邻内存位置上的。另一种顺序是列优先顺序,它意味着每列中的数据项是被存放在相邻内存位置上的。由于一些历史原因,行和列优先顺序又分别称为C和Fortran顺序。
6.2 数组排序
方法、函数 | 说明、示例 |
直接排序:ndarray自带的sort方法 | >>arr = np.array([0,5,4,3,2]) >> arr.sort() >> arr [out]:array([0, 2, 3, 4, 5]), sort方法为就地排序,会改变arr值 |
直接排序:np.sort函数 | >> arr1=np.array([0,5,4,3,2]) >> np.sort(arr1) [out]:array([0, 2, 3, 4, 5]) >>arr1 [out]:array([0, 5, 4, 3, 2]), np.sort函数会对原arr进行复制后排序 |
间接排序:np.argsort | >> # 使用np.argsort 进行间接排序分为三步 step1:生成原序列的索引值 >> arr2=np.array([0, 5, 4, 3, 2]) # 索引对应为:0:0,5:1,4:2,3:3,2:4 step2:对数组进行排序,返回排序后的索引序列 >> indexer=arr2.argsort() >> indexer # 索引对应为:0:0,2:4,3:3,4:2,5:1 [out]:array([0, 4, 3, 2, 1], dtype=int64) step3: 通过索引或切片返回排序后的数组 arr2[indexer] [out]:array([0, 2, 3, 4, 5]) |
间接排序:np.lexsort | 适用于一次性对多个键数组执行间接排序 # 使用np.lexsort与np.argsort总体一致 >> a=np.array([2,5,8,4,3,7,6]) >> b=np.array([9,4,0,4,0,2,1]) >> indexer=np.lexsort((a,b)) >> indexer 过程为:首先对a和b同时进行索引,然后优先对b进行升序排序,返回索引序列,对于b中具有相同值的元素,则按照索引对应a元素的大小确定序列 |
七、线性代数(numpy.linalg)
在计算上,数组可执行矩阵的运算。Numpy的线性代数模块封装在linalg中,引用方式为:import numpy.linalg
7.1 矩阵和向量积(Matrix and vector products)
方法 | 说明 |
numpy.dot(a, b, out=None) | Dot product of two arrays. 两个数组的点积。 |
linalg.multi_dot(arrays, *, out=None) | Compute the dot product of two or more arrays in a single function call, while automatically selecting the fastest evaluation order. 在单个函数调用中计算两个或更多数组的点积,同时自动选择最快的求值顺序。 |
numpy.vdot(a, b, /) | Return the dot product of two vectors. 返回两个向量的点积。 |
numpy.inner(a, b, /) | Inner product of two arrays. 两个数组的内积。 |
numpy.outer(a, b, out=None) | Compute the outer product of two vectors. 计算两个向量的外积。 |
numpy.matmul(x1, x2, /, out=None, *, casting='same_kind', order='K') | Matrix product of two arrays. 两个数组的矩阵乘积。 |
numpy.tensordot(a, b, axes=2) | Compute tensor dot product along specified axes. 沿指定轴计算张量点积。 |
numpy.einsum(subscripts) | Evaluates the Einstein summation convention on the operands. 计算操作数上的爱因斯坦求和约定。 |
numpy.linalg.matrix_power)(a, n) | Raise a square matrix to the (integer) power n. 将方阵提升为(整数)n次方。 |
numpy.kron(a, b) | Kronecker product of two arrays. 两个数组的Kronecker乘积。 |
7.2 分解(Decompositions)
方法 | 说明 |
numpy.linalg.cholesky(a) | Cholesky decomposition. Cholesky分解 |
numpy.linalg.qr(a, mode='reduced') | Compute the qr factorization of a matrix. 计算矩阵的QR分解。 |
numpy.linalg.svd(a, full_matrices=True, compute_uv=True, hermitian=False) | Singular Value Decomposition. 奇异值分解 |
7.3 矩阵特征值(Matrix eigenvalues)
方法 | 说明 |
numpy.linalg.eig(a) | Compute the eigenvalues and right eigenvectors of a square array. 计算方阵的特征值和右特征向量。 |
numpy.linalg.eigh(a) | Return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. 返回复数Hermitian(共轭对称)或实对称矩阵的特征值和特征向量 |
numpy.linalg.eigvals(a) | Compute the eigenvalues of a general matrix. 计算通用矩阵的特征值。 |
numpy.linalg.eigvalsh(a) | Compute the eigenvalues of a complex Hermitian or real symmetric matrix. 计算复杂的Hermitian或实对称矩阵的特征值。 |
7.4 范数和其他数字(Norms and other numbers)
方法 | 说明 |
numpy.linalg.norm(x, ord=None, axis=None, keepdims=False) | Matrix or vector norm. 矩阵或向量范数。 |
numpy.linalg.cond(x, p=None) | Compute the condition number of a matrix. 计算矩阵的条件数。 |
numpy.linalg.det(a) | Compute the determinant of an array. 计算数组的行列式。 |
numpy.linalg.matrix_rank (A, tol=None, hermitian=False) | Return matrix rank of array using SVD method 使用SVD方法返回数组的矩阵的rank |
numpy.linalg.slogdet(a) | Compute the sign and (natural) logarithm of the determinant of an array. 计算数组行列式的符号和(自然)对数。 |
numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None) | Return the sum along diagonals of the array. 返回数组的迹。 |
7.5 解方程和逆矩阵( Solving equations and inverting matrices)
方法 | 说明 |
numpy.linalg.solve(a, b) | Solve a linear matrix equation, or system of linear scalar equations. 求解线性矩阵方程或线性标量方程组。 |
numpy.linalg.tensorsolve(a, b, axes=None) | Solve the tensor equation a x = b for x. 对x求解张量方程a x = b。 |
numpy.linalg.lstsq(a, b, rcond='warn') | Return the least-squares solution to a linear matrix equation. 返回线性矩阵方程的最小二乘解。 |
numpy.linalg.inv(a) | Compute the (multiplicative) inverse of a matrix. 计算矩阵的(乘法)逆。 |
numpy.linalg.pinv(a, rcond=1e-15, hermitian=False) | Compute the (Moore-Penrose) pseudo-inverse of a matrix. 计算矩阵的(Moore-Penrose)伪逆。 |
numpy.linalg.tensorinv)(a[, ind]) | Compute the ‘inverse’ of an N-dimensional array. 计算N维数组的“逆”。 |
八、生成伪随机数(numpy.random)
引用:import random
方法 | 说明 |
np.random.seed(a=None,version=2) | 向随机数生成器传递随机状态种子,即不同运行次数的随机数生成器生成的结果一致 |
np.random.permutation(x) x:int,array,ndarray | 生成一个序列的随机排列,或生成一个随机排列的范围 >> np.random.permutation(3) [out]:array([1, 2, 0]) >> np.random.permutation([3,5,6]) [out]:array([6, 5, 3]) >>np.random.permutation(np.arange(6).reshape(2,3)) [out]:array([[3, 4, 5], [0, 1, 2]]) |
np.random.shuffle(x,random=None) | Shuffle array-like x in place,and return None 对序列x进行就地排列 >> listx=[1,2,3] >> np.random.shuffle(listx) [out]:无结果(None) >>listx [out]:[2, 1, 3] 可见,是直接改变序列值 >> arrx=np.arange(6).reshape(2,3) >> np.random.shuffle(arrx) >> arrx [out]:array([[3, 4, 5], [0, 1, 2]]) |
np.random.rand(d0,d1,d2,...,dn) 参数d为维数 | populate a uniform distribution over[0,1) 生成均匀分布样本值 >> np.random.rand(1,2) [out]:array([[0.65426618, 0.79308974]]) |
np.random.randint(a,b,size) | 生成指定区间的随机整数样本 >> np.random.randint(2,5,(1,2)) [out]: array([[4, 2]]) |
np.random.randn(d0,d1,...,dn) | 生成标准正态分布样本(Standard Normal Distribution) >> np.random.randn(1,2) [out]:array([[ 0.09815597, -0.0979203 ]]) |
np.random.normal(loc=0,scale=1,size=None) loc: Mean of the distribution scale:standard deviation of the distribution | 生成正态分布样本(Normal Distribution) >> np.random.normal(1,1,(1,2)) [out]:array([[-0.50851236, 1.05082552]]) |
np.random.beta(a,b,size) | 生成Beta分布样本(Beta distribution) >> np.random.beta(1,2,(1,2)) [out]:array([[0.89317546, 0.35695625]]) |
np.random.chisquare(df,size) df 为自由度 | 生成卡方分布(chi-square distribution)样本 >> np.random.chisquare(2) <br> [out]:0.6408878838735412 |
np.random.gamma(shape,scale,size) | 生成Gamma分布的样本值 >> np.random.gamma(1,1,(1,2)) [out]:array([[1.60048009, 1.68275304]]) |
np.random.uniform(a,b,size) | 生成指定区间[a,b)的均匀分布样本 >> np.random.uniform(2,5,(1,2)) [out]:array([[4.84427127, 4.46865392]]) |
九、 高级数组操作
9.1 数组合并与拆分
* 数组合并
分类 | 函数 | 说明 |
水平合并 | np.hstack(tup) tup:待合并的数组构成的元组,在待合并的轴向上需要尺寸相同 | >> arr1=np.arange(12).reshape(3,4) >> arr2=np.random.randint(1,50,(3,2)) >> np.hstack((arr1,arr2)) [out]:array([[ 0, 1, 2, 3, 18, 21],[ 4, 5, 6, 7, 9, 18],[ 8, 9, 10, 11, 41, 24]]) |
np.concatenate((a1, a2, ...), axis=0, out=None) | 取值axis=1时,沿着水平合并 >> np.concatenate((arr1,arr2),axis=1) 输出结果同上 | |
np.column_stack(tup) | 原理是将一维数组转换为二维列向量后进行合并 np.column_stack((arr1,arr2)) 输出结果同上 | |
垂直合并 | np.vstack,np.row_stack,np.concatenate((a1, a2, ...), axis=0) | 同水平合并 |
* 数组拆分
函数 | 说明 |
np.split(ary, indices_or_sections, axis=0) | 沿着指定轴向进行拆分 indices: int or 1-D array 当indices为int时,沿轴向将数据切割成N等分; 当indices为1-d array时,如[2,3]时,等同于切割成: array[:2], array[2:3],array[3:] |
9.2 元素重复操作
9.2.1 np.repeat
np.repeat(a, repeats, axis=None)
Repeat elements of an array. repeats : int or array of ints
repeat可将数组元素在指定轴向上进行复制,具体应用如下:
* 仅设置repeats参数为int时,可将数组元素复制int次,但如果没有设置轴向,则数组会被扁平化
>> arr = np.random.randint(1,10,(2,2))
>> arr
[out]:array([[3, 7],
[8, 7]])
>> arr.repeat(2)
[out]:array([3, 3, 7, 7, 8, 8, 7, 7])
* 设置repeats参数为int,且指定轴向时,会在指定轴向上复制元素int次
>> arr.repeat(2,axis=0)
[out]:array([[3, 7],
[3, 7],
[8, 7],
[8, 7]])
* 设置repeats参数为list,且指定轴向时,会在指定轴向上依次复制元素
>> arr.repeat([2,3],axis=0)
[out]:array([[3, 7],
[3, 7],
[8, 7],
[8, 7],
[8, 7]])
>> arr.repeat([2,3],axis=1)
[out]:array([[3, 3, 7, 7, 7],
[8, 8, 7, 7, 7]])
9.2.2 np.tile
np.tile(A, reps)
Construct an array by repeating A the number of times given by reps.
tile的功能是沿指定轴向堆叠数组的副本。你可以形象地将其想象成“铺瓷砖”。
arr # arr.ndim=2,arr.shape=(2,2)
[out]:array([[3, 7],
[8, 7]])
* 当d(reps)≤A.ndim时,则铺贴后得到的数组维数不变:
>> arr1=np.tile(arr,2) # d(2)=1
>> arr1
[out]:array([[3, 7, 3, 7], # arr1.ndim=2,arr1.shape=(2,4)
[8, 7, 8, 7]])
>> arr3=np.tile(arr,(2,3)) # d((2,3))=2
>> arr3
[out]:array([[3, 7, 3, 7, 3, 7], #arr3.ndim=2,arr3.shape=(4,6)
[8, 7, 8, 7, 8, 7],
[3, 7, 3, 7, 3, 7],
[8, 7, 8, 7, 8, 7]])
* 当d(reps)>A.ndim时,则铺贴后得到的数组维数为d(reps):
>> arr2=np.tile(arr,(1,2,3)) # d((1,2,3))=3
>> arr2
[out]:array([[[3, 7, 3, 7, 3, 7], #arr2.ndim=3,arr2.shape=(1, 4, 6)
[8, 7, 8, 7, 8, 7],
[3, 7, 3, 7, 3, 7],
[8, 7, 8, 7, 8, 7]]])