Python 使用zip和np.Insert将零的部分插入numpy数组
我切掉了numpy数组的零,做了一些事情,想把它们重新插入到视觉中。我确实有这些部分的索引,并尝试使用numpy.insert和zip将零重新插入,但索引超出了范围,即使我从低端开始。例如:Python 使用zip和np.Insert将零的部分插入numpy数组,python,arrays,numpy,indexing,zip,Python,Arrays,Numpy,Indexing,Zip,我切掉了numpy数组的零,做了一些事情,想把它们重新插入到视觉中。我确实有这些部分的索引,并尝试使用numpy.insert和zip将零重新插入,但索引超出了范围,即使我从低端开始。例如: import numpy as np a = np.array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5]) a = a[a != 0] # cut zeros out zero_start = [3, 9, 13] zero_end = [5
import numpy as np
a = np.array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])
a = a[a != 0] # cut zeros out
zero_start = [3, 9, 13]
zero_end = [5, 10, 15]
# Now insert the zeros back in using the former indices
for ev in zip(zero_start, zero_end):
a = np.insert(a, ev[0], np.zeros(ev[1]-ev[0]))
>>> IndexError: index 13 is out of bounds for axis 0 with size 12
似乎他没有刷新循环中的数组大小。有什么建议或其他(更具python风格的)方法来解决这个问题吗?方法#1:使用-
我们还可以生成a
最初具有非零的实际索引,然后分配。因此,掩蔽的最后一步可以用这样的东西代替-
out[np.setdiff1d(np.arange(N),idx)] = a
方法#2:使用给定的
zero_start
和zero_end
作为数组-
insert_start = np.r_[zero_start[0], zero_start[1:] - zero_end[:-1]-1].cumsum()
out = np.insert(a, np.repeat(insert_start, zero_end - zero_start + 1), 0)
样本运行-
In [755]: a = np.array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])
...: a = a[a != 0] # cut zeros out
...: zero_start = np.array([3, 9, 13])
...: zero_end = np.array([5, 10, 15])
...:
In [756]: s0 = np.r_[zero_start[0], zero_start[1:] - zero_end[:-1]-1].cumsum()
In [757]: np.insert(a, np.repeat(s0, zero_end - zero_start + 1), 0)
Out[757]: array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])
保留
a==0
的副本,并使用该副本将nee值复制到零数组中<代码>分辨率=np.0…res[mask]=new_值
.Mhh,所以我应该使用您的代码而不是zip?现在无法运行,结果数组的长度仍然是9。@你确定吗?你得到的idx
是什么?知道了,寻找错误的变量,“out”产生结果!非常感谢,现在我将深入研究并尝试理解其背后的想法,我不习惯于掩蔽。在我的实际问题上对其进行了测试,您的“编辑”实际上在原始解决方案似乎失败的地方获得了正确的结果。现在接受答案,两个有效的,简短的和伟大的方法@看看新的:方法#2
也一样!:)
In [755]: a = np.array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])
...: a = a[a != 0] # cut zeros out
...: zero_start = np.array([3, 9, 13])
...: zero_end = np.array([5, 10, 15])
...:
In [756]: s0 = np.r_[zero_start[0], zero_start[1:] - zero_end[:-1]-1].cumsum()
In [757]: np.insert(a, np.repeat(s0, zero_end - zero_start + 1), 0)
Out[757]: array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])