我正在尝试“扩展”点(x,y,z)的二维numpy数组
nadir
,并用插值点填充空间中的间隙。如果存在大于某个容差的空间间隙 dist
,我想使用 np.insert
插入所需数量的 nan
行来填充该间隙,添加要在之后插值的 nan
点。
首先,我找到间隙,并查看需要在每个间隙中插入多少个点(行)才能达到所需的空间点密度:
import numpy as np
# find and measure gaps
nadir = nadir[~np.isnan(nadir).any(axis = 1)]
dist = np.mean(np.linalg.norm(np.diff(nadir[:,0:2], axis = 0), axis = 1), axis = 0) # mean distance for gap definition
gaps = np.where(np.linalg.norm(np.diff(nadir[:,0:2], axis = 0), axis = 1) > dist)[0] # gap locations
sizes = (np.linalg.norm(np.diff(nadir[:,0:2], axis = 0), axis = 1)[gaps] // dist).astype(int) # how many points to insert in each gap
我希望我能做的是将 ndarray 列表传递给
np.insert()
作为 values
参数,如下所示:
nadir = np.insert(nadir, gaps, [np.full((size, 3), np.nan) for size in sizes], axis = 0)
这样,在
gaps
中的每个索引处,都会插入相应的形状为 (size,3)
的空数组。但上面的代码不起作用:
"ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (616,) + inhomogeneous part."
我可以在循环中实现这一点,但一个好的矢量化方法将是理想的。有任何想法吗?同样,我的最终目标是使用插值在空间上填充 3D 数据中的空白,无需网格化,因此任何其他聪明的方法也可以工作!
要插入多行,索引数必须与行数匹配:
In [176]: x=np.arange(12).reshape(4,3)
In [177]: np.insert(x,[1,1,1,2,2,3],np.ones((6,3),int)+100,axis=0)
Out[177]:
array([[ 0, 1, 2],
[101, 101, 101],
[101, 101, 101],
[101, 101, 101],
[ 3, 4, 5],
[101, 101, 101],
[101, 101, 101],
[ 6, 7, 8],
[101, 101, 101],
[ 9, 10, 11]])