原题目可以在此处找到,链接:https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises.md
本文只摘选了一部分习题进行讲解,题号和原题号对应。
import numpy as np
Z = np.random.random((3,3,3))
print(Z)
import numpy as np
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
import numpy as np
Z = np.random.random(30)
m = Z.mean()
print(m)
方法一:
import numpy as np
Z = np.ones((10, 10))
Z[1:-1, 1:-1] = 0
print(Z)
方法二:
import numpy as np
Z = np.ones((10, 10))
Z[1:9, 1:9] = 0
print(Z)
方法三:
import numpy as np
Z = np.zeros((5, 5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=1)
print(Z)
Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
import numpy as np
Z = np.diag(1+np.arange(4), k=1) #k为偏移量,k=-1,表示斜对角线的下方,k=1,表示斜对角线的上方,k=0,无偏移
print(Z)
棋盘格是交错的数值。实际还是用到多维数组的切片原理。在多维数组的切片中,a(m,n),a[start:stop:step,start:stop:step],两个参数分别是行列限制。分三个步骤,第一设置一个8*8的空值,第二步把第一行隔一列设置1,每两行两列同样,第三步类似第二部,不过是从第二行开始,错开。
import numpy as np
Z = np.zeros((8, 8), dtype=int)
Z[1::2, ::2] = 1
Z[::2, 1::2] = 1
print(Z)
import numpy as np
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
找出最大值和最小值,然后把最大值和最小值分别用1和0表示,其他值则反映在0和1中间。
import numpy as np
Z = np.random.random((5, 5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)
import numpy as np
color = np.dtype([("r", np.ubyte, 1), # dtype结构化数据类型
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])
print(color)
import numpy as np
Z = np.dot(np.ones((5, 3)), np.ones((3, 2))) # ones((5,3)),里面的括号容易忘
print(Z)
import numpy as np
Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z)