Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用zip和np.Insert将零的部分插入numpy数组_Python_Arrays_Numpy_Indexing_Zip - Fatal编程技术网

Python 使用zip和np.Insert将零的部分插入numpy数组

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

我切掉了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, 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])