简单应用
矩阵创建及运算
1.手动创建矩阵 np.mat('str')
利用mat(‘字符串’)函数创建矩阵,其中字符串的 表示中,矩阵的行与行之间用分号隔开,行内的元素之间用空格隔开。
b = np.mat('1,2,3;4,5,6;7,8,9')
b
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
2.用numpy数组创建
(1)利用mat(ndArray)函数创建矩阵(利用reshape函数)
c = np.mat(np.arange(9).reshape(3,3))
c
matrix([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
np.mat(np.arange(9))
matrix([[0, 1, 2, 3, 4, 5, 6, 7, 8]])
(2)利用mat(ndArray)函数创建矩阵,矩阵中存放随机数。 利用numpy.random 模块中的函数生成
np.mat(np.random.rand()) 均匀分布
d = np.mat(np.random.rand(2,3))
d
matrix([[0.86252398, 0.1797843 , 0.82403237],
[0.07537403, 0.41183687, 0.22876233]])
np.mat(np.random.randn()) 正态分布
e = np.mat(np.random.randn(3,2))
e
matrix([[ 0.42051582, 0.0347029 ],
[ 0.36521207, 0.04668425],
[ 0.72528606, -1.55421898]])
np.mat(np.random.randint()) 随机整数
f = np.mat(np.random.randint(1,10,8).reshape(2,4))
f
matrix([[5, 8, 9, 2],
[9, 6, 3, 4]])
np.random.random(shape) 0-1的随机数 shape = [2,3] 两行三列
g = np.mat(np.random.random([2,3]))
g
matrix([[0.47401071, 0.35007318, 0.05321747],
[0.64951321, 0.97723439, 0.20699691]])
np.random.choice(a, size=None, replace=True, p=None) 从a中取size个数据a :如果a是单个变量,则采用np.arange(a)的形式 size :int 或者(int1,int2,...)的可选参数,决定了输出的shape 如果给定了(m,n,k),那么mnk就是shape eplace:布尔参数,可选。决定采集的数据是否有重复值 p :一维的数组参数,可选。对应着a中每个采样点的概率分布,没有说明就是均匀分布
h1 = np.random.choice(5,3)
h1 # array([0, 3, 2])
#取无重复的
h2 = np.random.choice(a=list('abcdefgh'),size=(2,2),replace=False)
h2
array([['d', 'c'],
['h', 'f']], dtype='
# 参数p
h3 = np.random.choice([1,2,3,4],20,True,p = [0.4,0.3,0.2,0.1])
h3
array([1, 2, 2, 3, 1, 3, 1, 3, 1, 3, 3, 2, 2, 1, 2, 3, 1, 2, 1, 1])
1-100内的5x5随机整数
np.random.randint(1,101,25).reshape(5,5)
array([[63, 43, 22, 80, 59],
[40, 40, 1, 82, 55],
[61, 33, 77, 94, 75],
[33, 59, 16, 35, 27],
[14, 89, 80, 38, 9]])
np.random.randint(1,101,[5,5])
array([[32, 97, 64, 10, 4],
[83, 87, 69, 46, 39],
[85, 16, 68, 71, 54],
[81, 98, 77, 24, 57],
[65, 62, 92, 15, 80]])
3.从已有矩阵创建新的矩阵 np.bmat()
A = np.eye(2)
A
array([[1., 0.],
[0., 1.]])
B = A*2
B
array([[2., 0.],
[0., 2.]])
C = np.bmat('A B;A B;B A')
C
matrix([[1., 0., 2., 0.],
[0., 1., 0., 2.],
[1., 0., 2., 0.],
[0., 1., 0., 2.],
[2., 0., 1., 0.],
[0., 2., 0., 1.]])
矩阵计算算数运算: + np.add() - np.subtract() * np.multiply() / np.divide() // np.floor_divide()
a = np.mat(np.array([2,6,5]))
b = np.mat(np.array([1,2,3]))
#add
a+b+a # matrix([[ 5, 14, 13]])
np.add(a,b) # matrix([[3, 8, 8]])
#subtract
np.subtract(a,b) # matrix([[1, 4, 2]])
# multiply
np.multiply(a,b) # matrix([[ 2, 12, 15]])
a*b.T # matrix([[29]])
a.T*b
matrix([[ 2, 4, 6],
[ 6, 12, 18],
[ 5, 10, 15]])
#divide
a/b
matrix([[2. , 3. , 1.66666667]])
np.divide(a,b)
matrix([[2. , 3. , 1.66666667]])
#floor_divide
np.floor_divide(a,b)
matrix([[2, 3, 1]], dtype=int32)模运算 remainder函数:逐个返回两个数组中元素相除后的余数 mod函数与remainder函数的功能完全一致 %操作符仅仅是remainder函数的简写 fmod 函数所得余数的正负由被除数决定,与除数的正负无关
m = np.mat(np.arange(-4,4))
m
matrix([[-4, -3, -2, -1, 0, 1, 2, 3]])
print('m:',m)
print('remainder:',np.remainder(m,2))
print('%-10s'%'mod:',np.mod(m,2))
print('%-10s'%'%',m%2)
m: [[-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]]
% [[0 1 0 1 0 1 0 1]]
print('%-10s'%'fmod',np.fmod(m,2))
fmod [[ 0 -1 0 -1 0 1 0 1]]
import numpy as np
通用函数
1、概念: 通用函数(ufunc)是一种对ndarray中的数据执行元素级运算的函 数。你可以将其看作简单函数(接受一个或多个标量值,并产生一个或多 过标量值)的矢量化包装器。通用函数的输入是一组标量,输出也是一组 标量,它们通常可以对应于基本数学运算,如加、减、乘、除等。
2、通用函数(ufunc)有两种类别:
(1)一元(unary)ufunc,它们接受一个数组。返回一个结果数组,当然也 能返回两个数组(modf函数),但是这种的不是很常见;
(2)二元(binary)ufunc,它们接受两个数组,并返回一个结果数组。
一元函数
a= np.mat(np.arange(-4,3))
a
matrix([[-4, -3, -2, -1, 0, 1, 2]])
np.fabs(a)
matrix([[4., 3., 2., 1., 0., 1., 2.]])
np.abs(a)
matrix([[4, 3, 2, 1, 0, 1, 2]])
b = np.mat(range(1,6))
b
matrix([[1, 2, 3, 4, 5]])
np.sqrt(b)
matrix([[1. , 1.41421356, 1.73205081, 2. , 2.23606798]])
np.square(b)
matrix([[ 1, 4, 9, 16, 25]], dtype=int32)
c = np.mat([1,2,np.e,np.e-1,4,10,100])
c
matrix([[ 1. , 2. , 2.71828183, 1.71828183, 4. , 10. , 100. ]])
np.log(c)
matrix([[0. , 0.69314718, 1. , 0.54132485, 1.38629436, 2.30258509, 4.60517019]])
np.log10(c)
matrix([[0. , 0.30103 , 0.43429448, 0.2350944 , 0.60205999, 1. , 2. ]])
np.log2(c)
matrix([[0. , 1. , 1.44269504, 0.78096668, 2. , 3.32192809, 6.64385619]])
#对原数据加1再取对数
np.log1p(c)
matrix([[0.69314718, 1.09861229, 1.31326169, 1. , 1.60943791, 2.39789527, 4.61512052]])
d = np.mat(np.array([[2.3,4.6],[1.2,1.8]]))
d
matrix([[2.3, 4.6],
[1.2, 1.8]])
np.ceil(d)
matrix([[3., 5.],
[2., 2.]])
#判断符号位
np.sign(d)
matrix([[1., 1.],
[1., 1.]])
np.floor(d)
matrix([[2., 4.],
[1., 1.]])
np.rint(d)
matrix([[2., 5.],
[1., 2.]])
e = np.mat([
[1,2,3],
[2,3,4]
])
#转换成浮点数
#np.rint(e)
e*1.0
matrix([[1., 2., 3.],
[2., 3., 4.]])
#modf() 分别返回小数部分和整数部分
d
matrix([[2.3, 4.6],
[1.2, 1.8]])
arr1,arr2 = np.modf(d) arr1
arr
matrix([[0.3, 0.6],
[0.2, 0.8]])
arr2
matrix([[2., 4.],
[1., 1.]])
#isnan() 判断是不是一个数
np.isnan(np.nan)
True
g = np.mat([0,np.pi/3,np.pi/4,np.pi/2,np.pi*3/4])
g
matrix([[0. , 1.04719755, 0.78539816, 1.57079633, 2.35619449]])
np.cos(g)
matrix([[ 1.00000000e+00, 5.00000000e-01, 7.07106781e-01, 6.12323400e-17, -7.07106781e-01]])
np.sin(g)
matrix([[0. , 0.8660254 , 0.70710678, 1. , 0.70710678]])
np.tan(g)
matrix([[ 0.00000000e+00, 1.73205081e+00, 1.00000000e+00, 1.63312394e+16, -1.00000000e+00]])
#设置输出小数的位数
np.set_printoptions(precision=3)
np.tan(g)
matrix([[ 0.000e+00, 1.732e+00, 1.000e+00, 1.633e+16, -1.000e+00]])
二元函数常用二元函数
import numpy as np
#准备三个矩阵
a = np.mat([1,2,3,4])
b = np.mat([5,6,7,8])
c = np.mat([9,10,11,12])
#np.power() 求幂
np.power(b,a) # matrix([[ 5, 36, 343,4096]],dtype=int32)
np.power(6,2) # 36
#求最大值maximum(),最小值mininum() .元素级运算(两个列表的元素个数要相同)
arr1 = np.mat([1,8,2,9])
arr2 = np.mat([6,5,1,10])
np.maximum(arr1,arr2) # matrix([[ 6, 8, 2, 10]])
np.minimum(arr1,arr2) # matrix([[1, 5, 1, 9]])
#greater>,greater_equal>= 得到一个布尔值矩阵或者数组
np.greater(arr1,arr2) # matrix([[False, True, True, False]])
# 逻辑与logical_and,或logical_or,非logical_xor
d = np.mat('2 0;1 0')
e = np.mat('0 2;1 0')
np.logical_and(d,e)
matrix([[False, False],
[ True, False]])
np.logical_or(d,e)
matrix([[ True, True],
[ True, False]])
自定义函数
(1) 定义一个函数 (2) 书写函数内容:使用 np.frompyfunc(函数名,输入的参数个数(int),输出值的个数(int))创建通用函数
#0设置普通函数(zero矩阵)
def copyshape(a):
return np.zeros_like(a)
ucopyshape = np.frompyfunc(copyshape,1,1)
f = np.mat('1 2;3 4')
ucopyshape(f)
matrix([[0, 0],
[0, 0]], dtype=object)
#1.自定义函数,返回所有元素的平方,传入一个,传出一个
def square(a):
return a**2
usquare = np.frompyfunc(square,1,1)
usquare(np.mat('1 3 5 7'))
matrix([[1, 9, 25, 49]], dtype=object)
#2.自定义函数,返回两个矩阵对应位的平方和,传入2个,输出1个
def square_add(a,b):
return a**2 + b**2
usquare_add = np.frompyfunc(square_add,2,1)
g1 = np.mat('1 2 3 4')
g2 = np.mat('6 7 8 9')
usquare_add(g1,g2)
matrix([[37, 53, 73, 97]], dtype=object)
#3.第一个返回平方,第二个返回立方
def square_cubic(a,b):
return a**2,b**3
usquare_cubic = np.frompyfunc(square_cubic,2,2)
usquare_cubic(np.mat('1 2 3'),np.mat('4 5 6'))(matrix([[1, 4, 9]], dtype=object), matrix([[64, 125, 216]], dtype=object))
add函数
#01.add.accunulate(axis决定方向)
递归作用于输入的数组,将存储运算的中间结果返回
import numpy as np
a = np.arange(9)
a # array([0, 1, 2, 3, 4, 5, 6, 7, 8])
np.add.accumulate(a)
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36], dtype=int32)
print(a.reshape(3,3))
np.add.accumulate(a.reshape(3,3))
[[0 1 2]
[3 4 5]
[6 7 8]]
array([[ 0, 1, 2],
[ 3, 5, 7],
[ 9, 12, 15]], dtype=int32)
np.add.accumulate(a.reshape(3,3),axis=1)
array([[ 0, 1, 3],
[ 3, 7, 12],
[ 6, 13, 21]], dtype=int32)
np.add.accumulate(a.reshape(3,3),axis=0)
array([[ 0, 1, 2],
[ 3, 5, 7],
[ 9, 12, 15]], dtype=int32)
#02.add.reduce()方法,求和 axis决定方向 , 参数为array不是矩阵
np.add.reduce(a) # 36
b = np.arange(12).reshape(3,4)
b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
np.add.reduce(b,axis=0) # array([12, 15, 18, 21])
np.add.reduce(b,axis=1) # array([ 6, 22, 38])
#03.add.reduceat() 需要输入一个数组以及索引值类表。按照区间的方法求和
a # array([0, 1, 2, 3, 4, 5, 6, 7, 8])
#相当于 sum(a[0:5]),sum(a[5:2]),sum(a[2:7]),sum(a[7:])
np.add.reduceat(a,[0,5,2,7])
array([10, 5, 20, 15], dtype=int32)
#04.add.outer(a,b) a的每个值,加上b的所有。作用于第一个参数的元素以及第二个参数的整体
c = np.array([1,3,5,7])
a # array([0, 1, 2, 3, 4, 5, 6, 7, 8])
np.add.outer(c,a)
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9],
[ 3, 4, 5, 6, 7, 8, 9, 10, 11],
[ 5, 6, 7, 8, 9, 10, 11, 12, 13],
[ 7, 8, 9, 10, 11, 12, 13, 14, 15]])
np.add.outer(np.mat('1 2;3 4'),np.mat('4,5,6,7'))
array([[[[ 5, 6, 7, 8]],
[[ 6, 7, 8, 9]]],
[[[ 7, 8, 9, 10]],
[[ 8, 9, 10, 11]]]])
线性代数应用
1.np.linalg.inv() 计算 逆矩阵
import numpy as np
a = np.mat('0 1 2;3 0 5;-2 7 3')
np.linalg.inv(a)
matrix([[-1.52173913, 0.47826087, 0.2173913 ],
[-0.82608696, 0.17391304, 0.26086957],
[ 0.91304348, -0.08695652, -0.13043478]])
np.linalg.inv(a)*a
matrix([[ 1.00000000e+00, -2.22044605e-16, 0.00000000e+00],
[ 0.00000000e+00, 1.00000000e+00, -1.11022302e-16],
[ 0.00000000e+00, 1.11022302e-16, 1.00000000e+00]])
2.np.linalg.solve() 解线性方程组
x − 2y + z = 0
2y − 8z = 8
−4x + 5y + 9z = −9
b = np.mat('1 -2 1;0 2 -8;-4 5 9')
value = np.array([0,8,-9])
x,y,z = np.linalg.solve(b,value)
print(x) # 29.0
print(y) # 16.0
print(z) # 3.0
3.特征值和特征向量 np.linalg.eigvals() ;np.;inalg.eig()
eigvals() 函数可以计算矩阵的特征值 eig()可以返回一个 包含 特征值与特征向量的 元组
c = np.mat('3 -2;1 0')
c
matrix([[ 3, -2],
[ 1, 0]])
#特征值
np.linalg.eigvals(c) # array([2., 1.])
#特征值和特征向量
np.linalg.eig(c)
(array([2., 1.]), matrix([[0.89442719, 0.70710678],
[0.4472136 , 0.70710678]]))
4.奇异值分解 np.linalg.svd()
在numpy.linalg模块 中的svd函数可以对矩阵进行奇异值分解。该函数返回3个矩阵—— U 、 Sigma和 V ,其中 U 和 V 是正交矩阵,Sigma包含输入矩阵的奇异值。
d = np.mat('4 11 14;8 7 -2')
d
matrix([[ 4, 11, 14],
[ 8, 7, -2]])
U,Sigma,V = np.linalg.svd(d,full_matrices=False)
U
matrix([[-0.9486833 , -0.31622777],
[-0.31622777, 0.9486833 ]])
Sigma
array([18.97366596, 9.48683298])
V
matrix([[-0.33333333, -0.66666667, -0.66666667],
[ 0.66666667, 0.33333333, -0.66666667]])
#转换成对角矩阵
np.diag(Sigma)
array([[18.97366596, 0. ],
[ 0. , 9.48683298]])
U*np.diag(Sigma)*V
matrix([[ 4., 11., 14.],
[ 8., 7., -2.]])
5.计算矩阵的行列式 np.linalg.det()
e = np.mat('3 4;5 6')
e
matrix([[3, 4],
[5, 6]])
np.linalg.det(e) # -1.9999999999999971
import numpy as np
# sort
a = np.mat('3 1 2; 0 5 4; 7 3 6')
a
matrix([[3, 1, 2],
[0, 5, 4],
[7, 3, 6]])
np.sort(a)
matrix([[1, 2, 3],
[0, 4, 5],
[3, 6, 7]])
np.sort(a,axis=1)
matrix([[1, 2, 3],
[0, 4, 5],
[3, 6, 7]])
np.sort(a,axis=0)
matrix([[0, 1, 2],
[3, 3, 4],
[7, 5, 6]])
# argsort()
print(a)
np.argsort(a)
[[3 1 2]
[0 5 4]
[7 3 6]]
matrix([[1, 2, 0],
[0, 2, 1],
[1, 2, 0]], dtype=int64)
print(a)
np.argsort(a,axis = 0)
[[3 1 2]
[0 5 4]
[7 3 6]]
matrix([[1, 0, 0],
[0, 2, 1],
[2, 1, 2]], dtype=int64)
排序函数
1、ndarray类的sort方法——可对数组进行原地排序;
2、argsort函数——返回输入数组排序后的下标;
3、sort函数——返回排序后的数组;
搜索函数
1. np.argmax函数——返回数组中最大值对应的下标 ,忽略NAN
arr1 = np.array([1 ,8 ,6 ,np.nan ,20 ,0])
arr1 # array([ 1., 8., 6., nan, 20., 0.])
np.argmax(arr1) # 3
2.np.nanargmax函数——返回数组中最大值对应的下标 ,不忽略NAN
arr1 # array([ 1., 8., 6., nan, 20., 0.])
np.nanargmax(arr1) # 4
3. argwhere( ) 返回符合条件的下标
arr1 # array([ 1., 8., 6., nan, 20., 0.])
np.where(arr1<8)# (array([0, 2, 5], dtype=int64),)
arr1<8 # array([ True, False, True, False, False, True])
np.argwhere(arr1<8)
array([[0],
[2],
[5]], dtype=int64)
4. searchsorted( ) 为指定的插入值寻找 维持 排序 的 索引位置。 使用二分法如果输入的 数组 不是 range() 之类,没有排序的,一定要先排序
a = np.array([0,1,70,3,4,80,90])
a.sort()
a # array([ 0, 1, 3, 4, 70, 80, 90])
index = np.searchsorted(a,60)
index # 4
#在不打乱 a 排序的基础上插入b .返回b 每个数如果插入的话对应的位置
b = np.array([-5,7])
b # array([-5, 7])
indices = np.searchsorted(a,b)
indices # array([0, 4], dtype=int64)
数组元素抽取
1 . np.extract( condition,arr ) --根据某个条件从数组中抽取元素
arr = np.array(np.arange(8))
arr # array([0, 1, 2, 3, 4, 5, 6, 7])
list2 = [x for x in range(20) if x%2==0]
list2 # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
condition = (arr%2==0)
condition
array([ True, False, True, False, True, False, True, False])
arr1 = np.extract(condition,arr)
arr1 # array([0, 2, 4, 6])
arr[arr%2==0] # array([0, 2, 4, 6])
arr2 = np.random.randint(0,50,20)
print(arr2)
np.extract((arr2%2==0),arr2)
[18 47 38 11 17 17 8 39 37 9 2 25 31 28 38 48 10 22 22 25] array([18, 38, 8, 2, 28, 38, 48, 10, 22, 22])
2. np.nonzero( ) 专门用来抽取非零元素
np.nonzero(np.arange(5))
(array([1, 2, 3, 4], dtype=int64),)
金融函数
1、fv函数——计算所谓的终值(future value),终值是基于一些假设给出的某个金融资产在未来某一时间点的价值。终值有以下4个参数决定——利率、期数、每期支付金额以及现值 语法格式如下: numpy.fv(rate, nper, pmt, pv, [ when='end’])
参数:
rate:每一期的利率(rate of interest)。
nper:期数。
pmt:payment。每期支付金额
pv:present value,现值。
when:{{‘begin’, 1}, {‘end’, 0}}, {string, int}, optional. 每一期的开头还是结尾付
np.fv(0.03/4,4*5,-10,-1000) # 1376.0963320407982
2、pv函数——计算现值(present value)是指资产在当前时刻的价值。现值有以下4个参数决定——利率、期数、每期支付金额以及终值 语法格式如下: numpy.fv(rate, nper, pmt, fv,[ when='end’])
参数:
rate:每一期的利率(rate of interest)。
nper:期数。
pmt:payment。每期支付金额
fv: future value,终值。
when:{{‘begin’, 1}, {‘end’, 0}}, {string, int}, optional. 每一期的开头还是结尾付
np.pv(0.03/4,4*5,-10,1376.0963320407982) # -1000.0
3、净现值(net present value)——定义为按折现率计算的净现金流之和。净现值是指投资方案所产生的【现金净流量】(流入-流出)以资金成本为贴现 率折现之后与原始投资额现值的差额 经济意义
NPV>0表示项目实施后,除保证可实现预定的收益率外,尚可获得更高的收益。 NPV<0表示项目实施后,未能达到预定的收益率水平,而不能确定项目已亏损。 NPV=0表示项目实施后的投资收益率正好达到预期,而不是投资项目盈亏平衡。
语法格式如下: numpy.npv(rate, values)
参数:
rate:折现率。
values: 现金流,正数代表‘收入’或‘取款’,负数代表‘投资’或‘存款’。 第一个值必须是初始的投资,也就是必须是负数
np.npv(0.281,[-100,39,59,55,20]) # -0.00847859163845488
4、 pmt函数——根据本金和利率计算每期需支付的金额。语法格式如下: numpy.pmt(rate, nper, pv[, fv=0, when='end’])
参数:
rate:每一期的利率(rate of interest)
nper:期数 pv:present value,现值
np.pmt(0.075/12,12.*15,200000) # -1854.0247200054619
5、nper函数——计算定期付款的期数。语法格式如下: numpy.nper(rate, pmt, pv, fv=0, when='end')
参数:
rate:每一期的利率(rate of interest)
pmt:每期支付的金额 pv:present value,现值 fv: 终值
np.nper(0.075/12,-2000,200000)/12 # 13.118548820826762
6、 rate函数——根据给定的付款期数、每期付款资金、现值和终值计算利率.语法格式如下: numpy.rate(nper, pmt, pv, fv)
参数:
nper :需还的期数
pmt:每期支付的金额
pv:present value,现值
fv: 终值
np.rate(12*13,-2000,200000,0)*12 # 0.07402216952376835
np.pmt(0.04/12,12*30,700000) # -3341.907068258177
-np.pmt(0.04/12,12*30,700000)*12*30-700000 # 503086.5445729436