插值后重塑

时间:2015-05-13 08:18:16

标签: python numpy grid scipy reshape

将数据插值到目标网格后,我无法将数据重新整形以匹配原始形状。我的数据的原始形状是900x900是行x列。在插值之后,我在目标网格的新大小为2506时具有1-D内插值数组。为了进一步处理,我需要2506x2506整形。

以下是我的情况:

#SOURCE GRID + DATA
xs = [  3.58892995,   3.60107571,   3.61322204, ...,  15.67397575,
    15.68906607,  15.70415559]
ys = [ 46.95258041,  46.95351109,  46.95444002, ...,  54.7344427 ,
    54.7335759 ,  54.7327068 ]
# data.shape => (900,900), e.g. (rows, columns)
data = [[-- 0.43 -- ..., -- -- --]
       [-- -- -- ..., -- 0.21 --]
       [-- -- -- ..., -- -- --]
        ..., 
       [-- 1 -- ..., -- -- --]
       [-- 0.12 -- ..., -- -- --]
       [-- -- -- ..., -- -- --]]

values = data.flatten()

#TARGET GRID
xt = np.linspace(2, 9, 2506)
yt = np.linspace(44, 52, 2506)

#INTERPOLATION
Z = griddata((xs, ys), values, (xt, yt), method='nearest')
#Z = [-- -- -- ..., 0.0 0.0 0.0]
#Z.shape -> (2506,) BUT i need it in (2506, 2506)
#Z = np.reshape(Z, (2506, 2506)) is not working ofc

我不确定是否使用mgrid,meshgrid或reshape如果正确的方法来解决这个问题。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

matplotlib中的Griddata可能更符合您的要求。您可以执行以下操作,

from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np

datatype = 'grid'

npts = 900
xs = uniform(-2, 2, npts)
ys = uniform(-2, 2, npts)

# define output grid.
xt = np.linspace(-2.1, 2.1, 2506)
yt = np.linspace(-2.1, 2.1, 2506)

#Input is a series of 900 points
if datatype is 'points':
    values = xs*np.exp(-xs**2 - ys**2)
    # grid the data.
    Z = griddata(xs, ys, values, xt, yt, interp='nn')

#Input is a 900 x 900 grid of x,y,z points 
elif datatype is 'grid':

    X, Y = np.meshgrid(xs,ys, indexing='ij')
    values = 2 - 2 * np.cos(X)*np.cos(Y) - np.cos(X - 2*Y)

    # grid the data.
    Z = griddata(X.ravel(), Y.ravel(), values.ravel(), xt, yt, interp='nn')


# contour the gridded data, plotting dots at the nonuniform data points.
CS = plt.contour(xt, yt, Z, 15, linewidths=0.5, colors='k')
CS = plt.contourf(xt, yt, Z, 15, cmap=plt.cm.RdYlBu_r)
plt.colorbar()

# plot data points.
plt.scatter(xs, ys, marker='o', c='b', s=5, zorder=10)
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.show()

根据需要,Z的大小为2506x2506。输入数据可以是一系列点(900 x位置,900 y位置和这些位置处的900值)或网格。我添加了一个数据类型变量来在它们之间进行更改。看起来您的输入数据是网格形式......

答案 1 :(得分:0)

用法是

xxs, yys = np.meshgrid(xs, ys, indexing='ij')
Z = griddata((xxs.ravel(), yys.ravel()), values,
             (xt[:,np.newaxis], yt[np.newaxis,:]),
             method='nearest')

您需要首先从valuesxsys数组中过滤掉屏蔽值。