首页 > 解决方案 > 有没有更快的方法从一维数组中的随机索引插入数据?

问题描述

我有一个一维数组,我在其中删除所有 NaN 以进行一些后期处理。在执行此操作时,我会跟踪 NaN 所在的索引(以便我可以重新构建此一维数组以进行进一步分析)。当我使用 np.insert 和 for 循环将 NaN/0 插入这些索引时处理数据后,需要 6 分钟。有没有更好的方法来执行此操作?

代码:

#%% 跟踪删除的索引,zf 是我正在处理的一维数组

inds, z_wo_nan = [],[]     
for i, ele in enumerate(zf):
    if np.isnan(ele) == True:
        inds.append(i)
        z_wo_nan.append(ele)

#%% inds 将用于重新构建 zf #%% ------后处理------

zphas_f = np.delete(zf, inds)
xf_f = np.delete(xf, inds)
yf_f =np.delete(yf, inds)
    
 
xy_f = np.concatenate((xf_f[None,:],yf_f[None,:], np.ones(xf_f.shape)[None,:]), axis=0  ).transpose()
xy_inv_f = np.linalg.pinv(xy_f)   
abc_f = np.matmul(xy_inv_f, zphas_f[:,None] )      
rem_plane = np.matmul(xy_f, abc_f)   
z_dd = zphas_f - rem_plane.transpose()[0]

plt.figure()
plt.scatter(xf_f,yf_f,c=zphas_f)    #2 with values, no 0 or nan

plt.figure()
plt.scatter(xf_f,yf_f,c=rem_plane.transpose()[0])    #2 with values, no 0 or nan


plt.figure()
plt.scatter(xf_f,yf_f,c=z_dd)    #2 with values, no 0 or nan

#%% 后处理完成------------------- #%% 插入删除的索引 - 插入 0 而不是 nan

idx_del = inds
val_del = 0

z_dd_f_rec = z_dd

for i in idx_del:
    z_dd_f_rec = np.insert(z_dd_f_rec,i,0)   # 6 min for processing!!!!!!!!!!!

建议的解决方案:

#%% 跟踪删除的索引

inds = np.where(np.isnan(zf))[0] # Finds all indices where there is NaN
indsf = np.where(~np.isnan(zf))[0] # Finds all indices where there is NaN

#%% 后处理 - 从新数组重建

z_demo = np.empty(np.shape(zf))
for i in inds:
    z_demo[i] = 0
      
for i,j in enumerate(indsf):
    z_demo[j] = z_dd_f_rec[i]

标签: pythonarrays

解决方案


  1. == True没用
  2. Numpy 具有高效地完成几乎所有事情的功能。看这个例子:
nan_indexes = np.where(np.isnan(zf))[0] # Finds all indices where there is NaN
zf_without_nan = zf[np.invert(np.isnan(zf))] # Takes only element that are not NaN
  1. 您不需要重新创建 zf,因为上面的函数不会修改其内容,但它们会创建新数组。
  2. 鉴于第 3 点,您不再需要nan_indexes第 2 点,因为 zf 未修改。
  3. 即使是 300 万个数字的数组,每行 2. 也需要几毫秒。

推荐阅读