[英]Interpolation of missing values in 3D data-array in python
我在以下問題上苦苦掙扎了很長一段時間,但還沒有找到可行的解決方案。
我想在我的數據數組 [in Python] 中插入缺失值 (nan)。 該數組的維度為 lon、lat、time——它是一個隨時間變化的柵格數據集。
不幸的是,在某些時間步長中所有值都丟失了,並且無法使用 lon 和 lat (2D) 進行插值。 這就是為什么我想出在時間軸上插值的想法。 我希望一個時間步的缺失值在完全相同的像素處與之前和之后的時間步的值進行插值。
你有什么想法嗎?
我目前的嘗試是:
" def arr_interp(array): arrN=np.array(array,copy=False) arrN[np.isnan(arrN)]=interpolate.interp2d(LAI.lat, LAI.lon, LAI.time, fill_value="nan" )
arr_interp(LAI)"
問題是 NaN 數據可能會形成塊,您無法從鄰居中插值。
一種解決方案是進行高斯塞德爾插值求解拉普拉斯方程,(它創建的數據使函數的曲率最小化)。
此代碼查找 NaN 值並執行 3D 插值。 我無權訪問您的數據,因此它是通過合成數據完成的。
import numpy as np
import matplotlib.pyplot as plt
# create data
print("Creating data...")
size = 10 # 3D matrix of size: size³
# create x,y,z grid
x, y, z = np.meshgrid(np.arange(0, size), np.arange(
0, size), np.arange(0, size))
def f(x, y, z):
"""function to create synthetic data"""
return np.sin((x+y+z)/2)
data = np.zeros((size, size, size))
data[x, y, z] = f(x, y, z)
# create corrupted data
sizeCorruptedData = int(data.size*.2) # 20% of data is corrupted
# create random x,y,z index for NaN values
xc, yc, zc = np.random.randint(0, size, (3, sizeCorruptedData))
corruptedData = data.copy()
corruptedData[xc, yc, zc] = np.nan
# Interpolate on NaN values
print("Interpolating...")
# get index of nan in corrupted data
nanIndex = np.isnan(corruptedData).nonzero()
interpolatedData = data.copy()
# make an initial guess for the interpolated data using the mean of the non NaN values
interpolatedData[nanIndex] = np.nanmean(corruptedData)
def sign(x):
"""returns the sign of the neighbor to be averaged for boundary elements"""
if x == 0:
return [1, 1]
elif x == size-1:
return [-1, -1]
else:
return [-1, 1]
#calculate kernels for the averages on boundaries/non boundary elements
for i in range(len(nanIndex)):
nanIndex = *nanIndex, np.array([sign(x) for x in nanIndex[i]])
# gauss seidel iteration to interpolate Nan values with neighbors
# https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method
for _ in range(100):
for x, y, z, dx, dy, dz in zip(*nanIndex):
interpolatedData[x, y, z] = (
(interpolatedData[x+dx[0], y, z] + interpolatedData[x+dx[1], y, z] +
interpolatedData[x, y+dy[0], z] + interpolatedData[x, y+dy[1], z] +
interpolatedData[x, y, z+dz[0]] + interpolatedData[x, y, z+dz[1]]) / 6)
# plot results
f, axarr = plt.subplots(2, 2)
axarr[0, 0].imshow(data[:, :, 1])
axarr[0, 0].title.set_text('Original Data')
axarr[0, 1].imshow(corruptedData[:, :, 1])
axarr[0, 1].title.set_text('Corrupted Data')
axarr[1, 0].imshow(interpolatedData[:, :, 1])
axarr[1, 0].title.set_text('Fixed Data')
axarr[1, 1].imshow(data[:, :, 1]-interpolatedData[:, :, 1])
axarr[1, 1].title.set_text('Error = Original-Fixed')
f.tight_layout()
plt.show()
這對我幫助很大-謝謝!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.