我需要在二维矩阵中填入缺失的值(给定为0),如何在numpyscipy中完成?scipy.interpolate.interp2d 函数,但我不太明白如何使它只填入零而不修改非零项。
下面是这个函数用来平滑图像的例子。https:/scipython.combookchapter-8-scipyexamplesscipyinterpolateinterp2d。
但这不是我想要的。我只是想填写零值。
例如,矩阵是
import numpy as np
mat = np.array([[1,2,0,0,4], [1,0,0,0,8], [0,4,2,2,0], [0,0,0,0,8], [1,0,0,0,1]])
mat
array([[1, 2, 0, 0, 4],
[1, 0, 0, 0, 8],
[0, 4, 2, 2, 0],
[0, 0, 0, 0, 8],
[1, 0, 0, 0, 1]])
在这个矩阵中,所有的零都必须用内插值代替,而原始值应保持不变。
你必须做一个决定 如何 你想填入零。 例如,你可以使用数组中的平均值。
mat[mat == 0] = np.average(mat)
mat
# array([[1, 2, 1, 1, 4],
# [1, 1, 1, 1, 8],
# [1, 4, 2, 2, 1],
# [1, 1, 1, 1, 8],
# [1, 1, 1, 1, 1]])
或者你也可以用一些函数的值来拟合非零的值 --- scipy.interpolate.interp2d
使用 "花键"(想想多项式)。
from scipy.interpolate import interp2d
ix = np.where(mat != 0)
f = interp2d(ix[0], ix[1], mat[ix].flatten(), kind='linear')
mat2 = mat.copy()
mat2[mat==0] = f(range(5), range(5)).T[mat==0]
mat2
# array([[ 1, 2, 3, 4, 4],
# [ 1, 1, 1, 1, 8],
# [ 4, 4, 2, 2, 11],
# [ 4, 3, 2, 1, 8],
# [ 1, 0, 0, 0, 1]])
不过我想你会发现这种方法很麻烦,尤其是对于这么小的数据集。
你也可以看看其他的 归因方法,如最近的邻居等。