Python数据分析–Numpy常用函数介绍(7)–Numpy中矩阵和通用函数

在NumPy中,矩阵是 ndarray 的子类,与数学概念中的矩阵一样,NumPy中的矩阵也是二维的,可以使用 mat 、 matrix 以及 bmat 函数来创建矩阵。

一、创建矩阵

mat 函数创建矩阵时,若输入已为 matrix 或 ndarray 对象,则不会为它们创建副本。 因此,调用 mat() 函数和调用 matrix(data, copy=False) 等价。

1) 在创建矩阵的专用字符串中,矩阵的行与行之间用分号隔开,行内的元素之间用空格隔开。使用如下的字符串调用 mat 函数创建矩阵:

import numpy as np  A = np.mat('1 2 3; 4 5 6; 7 8 9') print("Creation from string:", A)

运行结果:

Creation from string:  [[1 2 3]  [4 5 6]  [7 8 9]]

2)用T属性获取转置矩阵

print("transpose A:", A.T)  # 用T属性获取转置矩阵

3)用I属性获取逆矩阵

print("Inverse A:", A.I)  # 用I属性获取逆矩阵

4)用NumPy数组进行创建矩阵

B = np.mat(np.arange(9).reshape(3, 3)) print("Creation from array:", B)#使用NumPy数组进行创建

上述运行结果:

Creation from string: 
[[1 2 3] [4 5 6] [7 8 9]] transpose A:
[[
1 4 7] [2 5 8] [3 6 9]] Inverse A:
[[
3.15251974e+15 -6.30503948e+15 3.15251974e+15] [-6.30503948e+15 1.26100790e+16 -6.30503948e+15] [ 3.15251974e+15 -6.30503948e+15 3.15251974e+15]] Creation from array:
[[0 1 2] [3 4 5] [6 7 8]]

二、从已有矩阵创建新矩阵

希望利用一些已有的较小的矩阵来创建一个新的大矩阵。这可以用 bmat 函数来实现。这里的 b 表示“分块”, bmat 即分块矩阵(block matrix)。

1)先创建一个3*3的单位矩阵:

C = np.eye(3) print("C:",C)

运行结果:

C:  [[1. 0. 0.]  [0. 1. 0.]  [0. 0. 1.]]

2)创建一个与C同型的矩阵,乘以2

D = 2 * C print ("D:",D)

运行结果:

D: 
[[2. 0. 0.] [0. 2. 0.] [0. 0. 2.]]

3)使用字符串创建复合矩阵:

字符串的格式与 mat 函数中一致,只是在这里你可以用矩阵变量名代替数字:

print("Compound matrixn", np.bmat("C D;C D"))

运行结果:

Compound matrix:  [[1. 0. 0. 2. 0. 0.]  [0. 1. 0. 0. 2. 0.]  [0. 0. 1. 0. 0. 2.]  [1. 0. 0. 2. 0. 0.]  [0. 1. 0. 0. 2. 0.]  [0. 0. 1. 0. 0. 2.]]

三、通用函数

通用函数的输入是一组标量,输出也是一组标量,它们通常可以对应于基本数学运算,如加、减、乘、除等。

1、使用NumPy中的 frompyfunc 函数,通过一个Python函数来创建通用函数,步骤如下:

1)定义一个回答某个问题的Python函数

2)用 zeros_like 函数创建一个和 a 形状相同,并且元素全部为0的数组 result

3)将刚生成的数组中的所有元素设置其值为42

2、在 add 上调用通用函数的方法

通用函数并非真正的函数,而是能够表示函数的对象。通用函数有四个方法,不过这些方法只对输入两个参数、输出一个参数的ufunc对象有效,例如 add 函数。

其他不符合条件的ufunc对象调用这些方法时将抛出 ValueError 异常。因此只能在二元通用函数上调用这些方法。以下将逐一介绍这4个方法:

 reduce()、accumulate()、 reduceat()、outer()

1) 沿着指定的轴,在连续的数组元素之间递归调用通用函数,即可得到输入数组的规约(reduce)计算结果。

对于 add 函数,其对数组的reduce计算结果等价于对数组元素求和。调用reduce 方法:

a = np.arange(9) print("Reduce:", np.add.reduce(a)) #调用add函数的reduce方法

运行结果:

Reduce 36

2) accumulate 方法同样可以递归作用于输入数组

在 add 函数上调用 accumulate 方法,等价于直接调用 cumsum 函数。在 add 函数上调用 accumulate 方法:

print( "Accumulate", np.add.accumulate(a)) #调用add函数的accumulate方法

运行结果:

Accumulate [ 0  1  3  6 10 15 21 28 36]

3)educeat 方法需要输入一个数组以及一个索引值列表作为参数。

print ("Reduceat", np.add.reduceat(a, [0, 5, 2, 7]))

educeat 方法的作用是,在数列a中,分别计算索引间的累加,比如上述的 [0, 5, 2, 7],分别计算索引0-5,5-2(5>2,所以直接取索引为5的数据),2-7,7-(-1) 等四组序列形成的

Python数据分析--Numpy常用函数介绍(7)--Numpy中矩阵和通用函数比如,0-5就是计算A-E列中的数据,结果为10;5-2,直接取索引为5,即F的数据5;2-7,即B-G的计算结果为20;7-(-1)即索引7到最后,也即H、I的计算结果为15。

Python数据分析--Numpy常用函数介绍(7)--Numpy中矩阵和通用函数

4)outer 方法

返回一个数组,它的秩(rank)等于两个输入数组的秩的和。它会作用于两个输入数组之间存在的所有元素对。在 add 函数上调用 outer 方法:

print("Outer:n", np.add.outer(np.arange(3), a))

运行结果:

Outer:  [[ 0  1  2  3  4  5  6  7  8]  [ 1  2  3  4  5  6  7  8  9]  [ 2  3  4  5  6  7  8  9 10]]

四、算术运算

在NumPy中,基本算术运算符+、-和 * 隐式关联着通用函数 add 、 subtract 和 multiply ,对NumPy数组使用这些算术运算符时,对应的通用函数将自动被调用。除法包含

的过程则较为复杂,在数组的除法运算中涉及

三个通用函数 divide 、 true_divide 和floor_division ,以及两个对应的运算符 / 和 // 。
1、除法运算:

import numpy as np  a = np.array([2, 6, 5]) b = np.array([1, 2, 3])  print("Divide:n", np.divide(a, b), np.divide(b, a))

 除了divide()函数外,还有floor_divide(),以及运算符‘/’和‘//’,(‘/’和‘//’分别和divide和floor_divide作用一样)如下代码:

import numpy as np  a = np.array([2, 6, 5]) b = np.array([1, 2, 3])  print("Divide:n", np.divide(a, b), np.divide(b, a)) print("True Divide:n", np.true_divide(a, b), np.true_divide(b, a))#回除法的浮点数结果而不作截断  print("Floor Divide:n", np.floor_divide(a, b), np.floor_divide(b, a))  #返回整数结果 c = 3.14*b print("Floor Divide2:n", np.floor_divide(c, b), np.floor_divide(b, c)) #返回整数结果  print( "/ operator:n", a/b, b/a)  # "/"运算符相当于调用 divide 函数  print( "// operator:n", a//b, b//a) #运算符//对应于floor_divide 函数 print( "// operator2:n", c//b, b//c) 

运行结果:

Divide:  [2.         3.         1.66666667] [0.5        0.33333333 0.6       ] True Divide:  [2.         3.         1.66666667] [0.5        0.33333333 0.6       ] Floor Divide:  [2 3 1] [0 0 0] Floor Divide2:  [3. 3. 3.] [0. 0. 0.] / operator:  [2.         3.         1.66666667] [0.5        0.33333333 0.6       ] // operator:  [2 3 1] [0 0 0] // operator2:  [3. 3. 3.] [0. 0. 0.]

 2、模运算

计算模数或者余数,可以使用NumPy中的 mod 、 remainder 和 fmod 函数。当然,也可以使用 % 运算符。这些函数的主要差异在于处理负数的方式。

a = np.arange(-4, 4) print('a:',a) print ("Remainder", np.remainder(a, 2)) # remainder 函数逐个返回两个数组中元素相除后的余数 print ("Mod", np.mod(a, 2))  # mod 函数与 remainder 函数的功能完全一致 print ("% operator", a % 2)  # % 操作符仅仅是 remainder 函数的简写  print ("Fmod", np.fmod(a, 2))# fmod 函数处理负数的方式与 remainder 、 mod 和 % 不同

运行结果:

a: [-4 -3 -2 -1  0  1  2  3] Remainder [0 1 0 1 0 1 0 1] Mod [0 1 0 1 0 1 0 1] % operator [0 1 0 1 0 1 0 1] Fmod [ 0 -1  0 -1  0  1  0  1]

实际代码运行如下:Python数据分析--Numpy常用函数介绍(7)--Numpy中矩阵和通用函数

 

 

 

 

发表评论

相关文章

当前内容话题