56. 构造一个二维高斯矩阵(★★☆)
(提示: np.meshgrid, np.exp)
X, Y = np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10)) D = np.sqrt(X**2 + Y**2) sigma, mu = 1.0, 0.0 G = np.exp(-( (D-mu)**2 / (2.0*sigma**2) )) print (G)
57. 如何在二维数组的随机位置放置p个元素? (★★☆)
(提示: np.put, np.random.choice)
# Author: Divakar n = 10 p = 3 Z = np.zeros((n,n)) np.put(Z, np.random.choice(range(n*n), p, replace=False),1) print(Z)
58. 减去矩阵每一行的平均值 (★★☆)
(提示: mean(axis=,keepdims=))
# Author: Warren Weckesser X = np.random.rand(5, 10) # 新 Y = X - X.mean(axis=1, keepdims=True) # 旧 Y = X - X.mean(axis=1).reshape(-1, 1) print(Y)
59. 如何对数组通过第n列进行排序? (★★☆)
(提示: argsort)
# Author: Steve Tjoa Z = np.random.randint(0,10,(3,3)) print(Z) print(Z[ Z[:,1].argsort() ])
60. 如何判断一个给定的二维数组存在空列? (★★☆)
(提示: any, ~)
# Author: Warren Weckesser Z = np.random.randint(0,3,(3,10)) print((~Z.any(axis=0)).any())
61. 从数组中找出与给定值最接近的值 (★★☆)
(提示: np.abs, argmin, flat)
Z = np.random.uniform(0,1,10) z = 0.5 m = Z.flat[np.abs(Z - z).argmin()] print(m)
62. 思考形状为(1, 3)和(3, 1)的两个数组形状,如何使用迭代器计算它们的和? (★★☆)
(提示: np.nditer)
A = np.arange(3).reshape(3, 1) B = np.arange(3).reshape(1, 3) it = np.nditer([A, B, None]) for x, y, z in it: z[...] = x + y print (it.operands[2])
63. 创建一个具有name属性的数组类 (★★☆)
(提示: class method)
class NameArray(np.ndarray): def __new__(cls, array, name="no name"): obj = np.asarray(array).view(cls) obj.name = name return obj def __array_finalize__(self, obj): if obj is None: return self.info = getattr(obj, 'name', "no name") Z = NamedArray(np.arange(10), "range_10") print (Z.name)
64. 给定一个向量,如何让在第二个向量索引的每个元素加1(注意重复索引)? (★★★)
(提示: np.bincount | np.add.at)
# Author: Brett Olsen Z = np.ones(10) I = np.random.randint(0,len(Z),20) Z += np.bincount(I, minlength=len(Z)) print(Z) # Another solution # Author: Bartosz Telenczuk np.add.at(Z, I, 1) print(Z)