最近发现几道numpy题目,觉得很妙,前来分享.
使用数字 0 将一个全为 1 的 5x5 二维数组包围:
z1=np.zeros((5,5))
z1[1:-1,1:-1]=1
z1
array([[0., 0., 0., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 0., 0., 0.]])
创建一个 5x5 的二维数组,并设置值 1, 2, 3, 4 落在其对角线下方:
z2 = np.diag(np.arange(1,5), k=-1)
z2
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0]])
创建一个 10x10 的二维数组,并使得 1 和 0 沿对角线间隔放置:
Z = np.zeros((10, 10), dtype=int)
Z[1::2, ::2] = 1
Z[::2, 1::2] = 1
Z
array([[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]])
使用6种不同的方法去提取一个随机数组的整数部分:
c=np.random.uniform(0, 10, 10)
print("方法 1: ", c - c % 1)
print("方法 2: ", np.floor(c))
print("方法 3: ", np.ceil(c)-1)
print("方法 4: ", c.astype(int))
print("方法 5: ", np.trunc(c)
print(c//1)
方法 1: [3. 7. 1. 8. 0. 2. 4. 4. 4. 3.]
方法 2: [3. 7. 1. 8. 0. 2. 4. 4. 4. 3.]
方法 3: [3. 7. 1. 8. 0. 2. 4. 4. 4. 3.]
方法 4: [3 7 1 8 0 2 4 4 4 3]
方法 5: [3. 7. 1. 8. 0. 2. 4. 4. 4. 3.]
[3. 7. 1. 8. 0. 2. 4. 4. 4. 3.]
将二维数组的前两行进行顺序交换:
A = np.arange(25).reshape(5, 5)
A[[0,1]]=A[[1,0]]
A
array([[ 5, 6, 7, 8, 9],
[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
找到随机一维数组中前 p 个最大值:
Z = np.random.randint(1, 100, 100)
print(Z)
p = 9
Z[np.argsort(Z)[-p:]]
[92 41 25 12 84 87 48 25 40 14 3 40 78 27 85 41 89 95 93 10 15 83 15 18
72 53 44 36 66 19 71 95 82 26 96 36 93 90 59 87 29 66 58 68 21 86 12 12
83 15 94 46 37 85 65 80 52 9 23 22 7 98 77 94 67 63 25 8 76 49 76 66
31 79 18 79 94 77 84 98 45 91 33 48 43 93 94 26 11 53 72 85 73 5 62 9
77 30 67 57]
array([94, 94, 94, 94, 95, 95, 96, 98, 98])
统计随机数组中的各元素的数量:
Z = np.random.randint(0, 100, 25).reshape(5, 5)
print(Z)
np.unique(Z, return_counts=True) # 返回值中,第 2 个数组对应第 1个元素的数量
[[49 38 41 47 89]
[53 89 22 46 49]
[61 5 23 89 77]
[33 59 4 87 60]
[57 52 50 0 1]]
(array([ 0, 1, 4, 5, 22, 23, 33, 38, 41, 46, 47, 49, 50, 52, 53, 57, 59,
60, 61, 77, 87, 89]),
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3],
dtype=int64))
使用 NumPy 打印九九乘法表:
np.fromfunction(lambda i, j: (i + 1) * (j + 1), (9, 9))
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[ 2., 4., 6., 8., 10., 12., 14., 16., 18.],
[ 3., 6., 9., 12., 15., 18., 21., 24., 27.],
[ 4., 8., 12., 16., 20., 24., 28., 32., 36.],
[ 5., 10., 15., 20., 25., 30., 35., 40., 45.],
[ 6., 12., 18., 24., 30., 36., 42., 48., 54.],
[ 7., 14., 21., 28., 35., 42., 49., 56., 63.],
[ 8., 16., 24., 32., 40., 48., 56., 64., 72.],
[ 9., 18., 27., 36., 45., 54., 63., 72., 81.]])
求赞 >_<