numpy

2019-07-07  本文已影响0人  GXLiu_28

多维数组转成一维

利用numpy的flatten函数
例如,刚开始生成一个3x3的矩阵,注意用a=[ ]生成的是一个列表list,用numpy的array可以将其转换成矩阵

import numpy as np
a=[[1,2,3],[4,5,6],[7,8,9]]
array=np.array(a)
# output
1 2 3 
4 5 6
7 8 9

接下来我们将其转换成一维数组

array=array.flatten()
# output
1 2 3 4 5 6 7 8 9

创建对角矩阵

import numpy as np
I=np.diag([1,1,1,1,1]) #I=np.diag([1]*5) is ok too
print(I)
# output
[[1 0 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]

# 也可以用 np.eye 方法
A=np.matrix([
    [0, 1, 0, 0],
    [0, 0, 1, 1], 
    [0, 1, 0, 0],
    [1, 0, 1, 0]],
    dtype=float)
A_hat=A+np.eye(A.shape[0])
print(A_hat)
# output
[[1. 1. 0. 0.]
 [0. 1. 1. 1.]
 [0. 1. 1. 0.]
 [1. 0. 1. 1.]]

矩阵乘法

import numpy as np
# 推荐用np.matrix,它可以直接*就是矩阵乘法了
A=np.matrix([[0,0,1,0,0],
            [0,0,1,0,0],
            [1,1,0,1,1],
            [0,0,1,0,1],
            [0,0,1,1,0]])
B=np.matrix([[1,2],
             [2,4],
             [7,10],
             [-5,3],
             [4,6]])
C=A*B
print(C)

# 另一种方法是用array,结果一样的
A=np.array([[0,0,1,0,0],
            [0,0,1,0,0],
            [1,1,0,1,1],
            [0,0,1,0,1],
            [0,0,1,1,0]])
B=np.array([[1,2],
             [2,4],
             [7,10],
             [-5,3],
             [4,6]])
C=np.dot(A,B)
print(C)
# output
[[ 7 10]
 [ 7 10]
 [ 2 15]
 [11 16]
 [ 2 13]]

矩阵次方运算

A=np.array([[1,2],
             [2,4],
             [7,10],
             [-5,3],
             [4,6]])
B=np.power(A,2)
print(B)
# output
[[  1   4]
 [  4  16]
 [ 49 100]
 [ 25   9]
 [ 16  36]]

# 当只想对对角线上的值次方运算时,用matrix(它只用来计算对角线上的元素的次方,对角线上也不能有0!)
A=np.matrix([
    [2, 0, 0, 0],
    [0, 3, 0, 0], 
    [0, 0, 4, 0],
    [0, 0, 0, 16]],
    dtype=float)
B=A**-1 #即A中的非零元素开负一次方
print(B)
# output
[[0.5        0.         0.         0.        ]
 [0.         0.33333333 0.         0.        ]
 [0.         0.         0.25       0.        ]
 [0.         0.         0.         0.0625    ]]

求数组某一范围的和

import numpy as np
a=np.array([1,2,3,5,6])
print(np.sum(a[2:5]))
# output
14
上一篇 下一篇

猜你喜欢

热点阅读