81. 考虑一个数组Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14],如何生成一个数组R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], …,[11,12,13,14]]? (★★★)
(提示: stride_tricks.as_strided)
# Author: Stefan van der Walt Z = np.arange(1,15,dtype=np.uint32) R = stride_tricks.as_strided(Z,(11,4),(4,4)) print(R)
82. 计算矩阵的秩 (★★★)
(提示: np.linalg.svd)
# Author: Stefan van der Walt Z = np.random.uniform(0,1,(10,10)) U, S, V = np.linalg.svd(Z) # Singular Value Decomposition rank = np.sum(S > 1e-10) print(rank)
83. 如何找出数组中出现频率最高的值?(★★★)
(提示: np.bincount, argmax)
Z = np.random.randint(0,10,50) print(np.bincount(Z).argmax())
84. 从一个10x10的矩阵中提取出连续的3x3区块(★★★)
(提示: stride_tricks.as_strided)
# Author: Chris Barker Z = np.random.randint(0,5,(10,10)) n = 3 i = 1 + (Z.shape[0]-3) j = 1 + (Z.shape[1]-3) C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides) print(C)
85.创建一个满足 Z[i,j] == Z[j,i]的二维数组子类 (★★★)
(提示: class method)
# Author: Eric O. Lebigot # Note: only works for 2d array and value setting using indices class Symetric(np.ndarray): def __setitem__(self, index, value): i,j = index super(Symetric, self).__setitem__((i,j), value) super(Symetric, self).__setitem__((j,i), value) def symetric(Z): return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric) S = symetric(np.random.randint(0,10,(5,5))) S[2,3] = 42 print(S)
86. 考虑p个 nxn 矩阵和一组形状为(n,1)的向量,如何直接计算p个矩阵的乘积(n,1)? (★★★)
(提示: np.tensordot)
# Author: Stefan van der Walt p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S) # It works, because: # M is (p,n,n) # V is (p,n,1) # Thus, summing over the paired axes 0 and 0 (of M and V independently), # and 2 and 1, to remain with a (n,1) vector.
87. 对于一个16x16的数组,如何得到一个区域的和(区域大小为4x4)? (★★★)
(提示: np.add.reduceat)
# Author: Robert Kern Z = np.ones((16,16)) k = 4 S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), np.arange(0, Z.shape[1], k), axis=1) print(S)
88. 如何利用numpy数组实现Game of Life? (★★★)
(提示: Game of Life , Game of Life有哪些图形?)
# Author: Nicolas Rougier def iterate(Z): # Count neighbours N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] + Z[1:-1,0:-2] + Z[1:-1,2:] + Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:]) # Apply rules birth = (N==3) & (Z[1:-1,1:-1]==0) survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1) Z[...] = 0 Z[1:-1,1:-1][birth | survive] = 1 return Z Z = np.random.randint(0,2,(50,50)) for i in range(100): Z = iterate(Z) print(Z)
89. 如何找到一个数组的第n个最大值? (★★★)
(提示: np.argsort | np.argpartition)
Z = np.arange(10000) np.random.shuffle(Z) n = 5 # Slow print (Z[np.argsort(Z)[-n:]]) # Fast print (Z[np.argpartition(-Z,n)[:n]])