python - 有没有更快的方法从一维数组中的随机索引插入数据?
问题描述
我有一个一维数组,我在其中删除所有 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]
解决方案
== True
没用- 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
- 您不需要重新创建 zf,因为上面的函数不会修改其内容,但它们会创建新数组。
- 鉴于第 3 点,您不再需要
nan_indexes
第 2 点,因为 zf 未修改。 - 即使是 300 万个数字的数组,每行 2. 也需要几毫秒。
推荐阅读
- java - Java 8 Hashmap 内部结构
- ios - Xcode 不允许我对 UIView 使用 NSObject 的 init() 函数
- python - 使用 pandas 获取聚合行值的样本
- c# - HasAlternateKey 允许重复输入
- apache-kafka - 设置配置保留.ms=3600000 仍然没有从 Kafka 中删除数据
- mongodb - Mongo加入特定列
- sql-server - 选择列作为 SQL SERVER 中另一个表中值的列名
- node.js - 将 json 对象存储到 Azure Blob 存储
- postgresql - 支持并行查询执行的 Google Cloud SQL Postgres 9.6
- java - 如何访问文件java中的每个单词?