【发布时间】:2020-02-18 22:35:54
【问题描述】:
有以下任务:
按列标准化矩阵。从列中的每个值减去平均值(列中),然后除以标准偏差(列中)。您的输出不应包含 nan (由零除引起)。将 Nans 替换为 1。不要使用 if 和 while/for。
我正在使用 numpy,所以我编写了以下代码:
def normalize(matrix: np.array) -> np.array:
res = (matrix - np.mean(matrix, axis = 0)) / np.std(matrix, axis = 0, dtype=np.float64)
return res
matrix = np.array([[1, 4, 4200], [0, 10, 5000], [1, 2, 1000]])
assert np.allclose(
normalize(matrix),
np.array([[ 0.7071, -0.39223, 0.46291],
[-1.4142, 1.37281, 0.92582],
[ 0.7071, -0.98058, -1.38873]])
)
答案是对的。
但是,我的问题是:如何避免被零除?如果我有一列相似数字,我将得到标准偏差 = 0 和结果中的 Nan 值。我该如何解决?不胜感激!
【问题讨论】: