使用 zip 和 np.insert 将零的部分插入到 numpy 数组中



我剪掉了一个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

似乎他没有刷新循环内的数组大小。有什么建议或其他(更pythonic)方法来解决这个问题吗?

方法#1:使用indexing -

# Get all zero indices
idx = np.concatenate([range(i,j+1) for i,j in zip(zero_start,zero_end)])
# Setup output array of zeros
N = len(idx) + len(a)
out = np.zeros(N,dtype=a.dtype)
# Get mask of non-zero places and assign values from a into those
out[~np.in1d(np.arange(N),idx)] = a

我们还可以生成实际的索引,其中a最初具有非零,然后分配。因此,遮罩的最后一步可以用这样的东西代替——

out[np.setdiff1d(np.arange(N),idx)] = a

方法#2:使用给定zero_startzero_end np.insert作为数组 -

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])

最新更新