1.创建一个边界值为1而内部都是0的数组,图例如下:
[提示:]解此题可以先把所有值都设置为1,这是大正方形;其次,把边界除外小正方形全部设置为0。
本题用到numpy的切片原理。多维数组同样遵循x[start:stop:step]的原理。
[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.]
1 import numpy as np 2 a=np.ones((10,10),int) 3 a[1:9,1:9]=0 4 print(a)
2.在数组主对角线上创建一个值为1,2,3,4的5x5矩阵,图例如下:
[1 0 0 0]
[0 2 0 0]
[0 0 3 0]
[0 0 0 4]
1 a[1,1] = 2 2 a[2,2] = 3 3 a[3,3] = 4 4 print(a)
3.数组归一化操作
生成一个随机的5*5矩阵,找出最大值和最小值,然后把最大值和最小值分别用1和0表示,其他值则介于在0和1中间。
[[0.41851145 0.27171482 0.91609303 0.44685116 0.01095894] [0.10210564 0.70589277 0.81580552 0.36898017 0.9900015 ] [0.78628395 0.83739597 0.3110785 0.1620625 0.29388605] [0.04237523 0.08155288 0.89594181 0.55891092 0.52291496] [0.3471473 0.92782236 0.1917479 0.37677106 0.58525168]] 0.9900014954356473 0.01095893529290426 [[0.41851145 0.27171482 0.91609303 0.44685116 0. ] [0.10210564 0.70589277 0.81580552 0.36898017 1. ] [0.78628395 0.83739597 0.3110785 0.1620625 0.29388605] [0.04237523 0.08155288 0.89594181 0.55891092 0.52291496] [0.3471473 0.92782236 0.1917479 0.37677106 0.58525168]]
1 import numpy as np 2 a=np.random.rand(5,5) 3 b=np.max(a) 4 c=np.min(a) 5 print(b) 6 print(c) 7 a[a==a.max()]=1 8 a[a==a.min()]=0 9 print(a)