我有一个大小为 48x80 的数组,现在我想将该数组扩展为一个大小为 117x192 的新数组。
我已经阅读了 scipy.interpolate ,但它没有提到扩展。

如何扩展数组并将值放入新数组中?

例如:
给定数组 A [[1,2,3],[4,5,6],[7,8,9]]

[1 2 3]
[4 5 6]
[7 8 9]

现在我想将数组 A 扩展到大小为 5x7 的数组 B
1 x 2 x 3
x x x x x
x x x x x
4 x 5 x 6
x x x x x
x x x x x
7 x 8 x 9

其中,用内插值替换这些“x”。

示例 2:
在更一般的数组中
[4 2 6 4]
[4 34 6 2]
[2 11 3 4]
[2 4 22 4]
[2 1 35 255]
[1 3 4 54]
[22 1 4 5]

如果我想要一个大小为 20x30 的新数组,我该怎么办

更新:
我发现有一个区别使@nicoguaro 的答案在我的情况下不起作用:

他的解决方案:
pts = np.array([[i,j] for i in np.linspace(0,1,n) for j in np.linspace(0,1,m)] )
grid_x, grid_y = np.mgrid[0:1:m*2j, 0:1:n*2j]

我的解决方案:
pts = np.array([[i,j] for i in np.linspace(0,2*m-1,m) for j in np.linspace(0,2*n-1,n)] )
grid_x, grid_y = np.mgrid[0:m*2, 0:n*2]

它导致不同的结果。事实上,他的解决方案在大多数情况下都有效,但我猜是 TIFF 文件

最佳答案

尽管 interpolate 没有针对此特定任务的功能,但您可以轻松使用内置选项来完成它。使用您提出的相同示例

[1 2 3]
[4 5 6]
[7 8 9]


1 x 2 x 3
x x x x x
x x x x x
4 x 5 x 6
x x x x x
x x x x x
7 x 8 x 9

我们可以使用这个代码
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot as plt

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
vals = np.reshape(A, (9))
pts = np.array([[i,j] for i in [0.0, 0.5, 1.0] for j in [0.0, 0.5, 1.0]] )
grid_x, grid_y = np.mgrid[0:1:7j, 0:1:5j]
grid_z = inter.griddata(pts, vals, (grid_x, grid_y), method='linear')

结果是
array([[ 1. ,  1.5,  2. ,  2.5,  3. ],
       [ 2. ,  2.5,  3. ,  3.5,  4. ],
       [ 3. ,  3.5,  4. ,  4.5,  5. ],
       [ 4. ,  4.5,  5. ,  5.5,  6. ],
       [ 5. ,  5.5,  6. ,  6.5,  7. ],
       [ 6. ,  6.5,  7. ,  7.5,  8. ],
       [ 7. ,  7.5,  8. ,  8.5,  9. ]])

或者,作为图像



在这种情况下,我使用 griddata 将在一组点 ( vals ) 上定义的集合函数 ( pts ) 插入到给定的直线网格(由 grid_xgrid_y 给出)。例如,如果您想对 $x$ 使用 nx 点,为 $y$ 使用 ny 点,则可以替换一行
grid_x, grid_y = np.mgrid[0:1:nx*1j, 0:1:ny*1j]

对于 nx=20ny=15 我们得到了这张图片

您可以在 documentation of the function 中查看更多示例。

更新: 包括示例 2,其中矩阵为
A = np.array([[4, 2, 6, 4],
            [4, 34, 6, 2],
            [2, 11, 3, 4],
            [2, 4, 22, 4],
            [2, 1, 35, 255],
            [1, 3, 4, 54],
            [22, 1, 4, 5]])

以及大小为 20x30 的新数组。代码如下
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot as plt

A = np.array([[4, 2, 6, 4],
            [4, 34, 6, 2],
            [2, 11, 3, 4],
            [2, 4, 22, 4],
            [2, 1, 35, 255],
            [1, 3, 4, 54],
            [22, 1, 4, 5]])
vals = np.reshape(A, (28))
pts = np.array([[i,j] for i in np.linspace(0,1,4) for j in np.linspace(0,1,7)] )
grid_x, grid_y = np.mgrid[0:1:20j, 0:1:30j]
grid_z = inter.griddata(pts, vals, (grid_x, grid_y), method='linear')

plt.matshow(A)
plt.matshow(grid_z)
plt.show()

生成的图像是:

关于python - 扩展二维数组并插入缺失值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26212122/

10-12 16:43
查看更多