使用Scipy的griddata在不规则网格(x和y)中对数据(d)进行格式化是数据集很多时的时间。但是,经度和纬度(x和y)总是相同的,只有数据(d)在变化。在这种情况下,一旦使用giddata,如何使用不同的d arrys重复该过程以实现更快的结果?
import numpy as np, matplotlib.pyplot as plt
from scipy.interpolate import griddata
x = np.array([110, 112, 114, 115, 119, 120, 122, 124]).astype(float)
y = np.array([60, 61, 63, 67, 68, 70, 75, 81]).astype(float)
d = np.array([4, 6, 5, 3, 2, 1, 7, 9]).astype(float)
ulx, lrx = np.min(x), np.max(x)
uly, lry = np.max(y), np.min(y)
xi = np.linspace(ulx, lrx, 15)
yi = np.linspace(uly, lry, 15)
grided_data = griddata((x, y), d, (xi.reshape(1,-1), yi.reshape(-1,1)), method='nearest',fill_value=0)
plt.imshow(grided_data)
plt.show()
上面的代码适用于d的一个数组。 但我有数百个其他阵列。
答案 0 :(得分:2)
griddata
的 nearest
最终使用NearestNDInterpolator
。这是一个创建迭代器的类,使用xi
调用它:
elif method == 'nearest':
ip = NearestNDInterpolator(points, values, rescale=rescale)
return ip(xi)
因此,您可以创建自己的NearestNDInterpolator
,并使用不同的xi
多次调用它。
但我认为在你的情况下你想要改变values
。查看该类的代码,我看到了
self.tree = cKDTree(self.points)
self.values = y
__call__
:
dist, i = self.tree.query(xi)
return self.values[i]
我不知道创建tree
与query
的相对成本。
因此,在使用values
之间更改__call__
应该很容易。看起来values
可能有多列,因为它只是在第一维上编制索引。
这个插补器非常简单,您可以使用相同的tree
想法编写自己的插值器。
这是一个最近的插值器,可让您重复相同点的插值,但不同的z
值。我还没有完成时间,看看它节省了多少时间
class MyNearest(interpolate.NearestNDInterpolator):
# normal interpolation, but returns the near neighbor indices as well
def __call__(self, *args):
xi = interpolate.interpnd._ndim_coords_from_arrays(args, ndim=self.points.shape[1])
xi = self._check_call_shape(xi)
xi = self._scale_x(xi)
dist, i = self.tree.query(xi)
return i, self.values[i]
def my_griddata(points, values, method='linear', fill_value=np.nan,
rescale=False):
points = interpolate.interpnd._ndim_coords_from_arrays(points)
if points.ndim < 2:
ndim = points.ndim
else:
ndim = points.shape[-1]
assert(ndim==2)
# simplified call for 2d 'nearest'
ip = MyNearest(points, values, rescale=rescale)
return ip # ip(xi) # return iterator, not values
ip = my_griddata((xreg, yreg), z, method='nearest',fill_value=0)
print(ip)
xi = (xi.reshape(1,-1), yi.reshape(-1,1))
I, data = ip(xi)
print(data.shape)
print(I.shape)
print(np.allclose(z[I],data))
z1 = xreg+yreg # new z data
data = z1[I] # should show diagonal color bars
只要z
具有与之前相同的形状(以及xreg
),z[I]
将为每个xi
返回最接近的值。
它也可以插入2d数据(例如(225,n)形)
z1 = np.array([xreg+yreg, xreg-yreg]).T
print(z1.shape) # (225,2)
data = z1[I]
print(data.shape) # (20,20,2)