Numpy 例题
-
生成一个一维数组,起始值为5,终点值为15,样本数为10个
import numpy as np a=np.arange(5,15) #a=np.array([5,6,7,8,9,10,11,12,13,14]) print(a)
[ 5 6 7 8 9 10 11 12 13 14]
-
输出对角矩阵
#第一种方法 import numpy as np a=np.zeros((3,3)) for i in range(3): for j in range(3): if(i==j): a[i][i]=1.0 elif(i!=j): a[i][j]=0.0 print(a)
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
#第二种方法 import numpy as np b=np.identity(3)#也可以用eye函数 print(b)
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
-
创造一个边界值为1而内部都是0的数组
#第一种方法 import numpy as np a = np.zeros((10,10),dtype=float) for i in range(0,10): for j in range(0,10): if i == 0 or i == 9 or j == 0 or j == 9: a[i][j] = 1 print(a)
[[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
#第二种方法 import numpy as np S = np.ones((10, 10)) S[1:9, 1:9] = 0 print(S)
[[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
-
生成一个5行10列的随机整数矩阵,数字范围在0~100之间
data1=np.random.randint(100,size=(5,10)) print(data1) print(data1[:2,:])
[[74 10 60 12 66 30 88 12 78 0]
[10 71 54 62 51 0 47 82 3 67]
[68 44 2 85 82 36 90 99 63 71]
[95 25 7 19 85 49 7 15 7 15]
[47 38 89 52 43 93 97 84 10 24]]
[[74 10 60 12 66 30 88 12 78 0]
[10 71 54 62 51 0 47 82 3 67]]
-
已知矩阵A和B如下,求两个矩阵相加和相乘
A=np.array([ [1,2,3], [4,5,6], [7,8,9] ]) B=np.array([ [1,1,1], [1,1,1], [1,1,1] ]) print(A+B) print(A.dot(B))
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
[[ 6 6 6]
[15 15 15]
[24 24 24]]
import numpy as np A=[[1,2,3],[4,5,6],[7,8,9]] B=[[1,1,1],[1,1,1],[1,1,1]] A=np.array(A) B=np.array(B) print("和为:",A+B) print("乘积为:",A*B)
和为: [[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
乘积为: [[1 2 3]
[4 5 6]
[7 8 9]]