In [178]: cell = np.array([1, 4, 4, 5, 5, 2, 5, 1, 1, 5])
In [179]: place = np.argwhere(cell == np.amax(cell)).flatten().tolist()
In [180]: place
Out[180]: [3, 4, 6, 9]
In [181]: np.insert(cell, place, 0)
Out[181]: array([1, 4, 4, 0, 5, 0, 5, 2, 0, 5, 1, 1, 0, 5])
In [182]: np.concatenate([cell[:3],[0],cell[3:4],[0],cell[4:6],[0],cell[6:9],[0] ,cell[9:]])
Out[182]: array([1, 4, 4, 0, 5, 0, 5, 2, 0, 5, 1, 1, 0, 5])
可以通过对place 值的某种列表迭代来概括构造连接列表。细节留给读者。
insert,有多个插入,使用mask 方法,我们可以对其进行逆向工程:
它在哪里插入了 0?
In [193]: res = np.insert(cell, place, 0)
In [194]: np.where(res==0)
Out[194]: (array([ 3, 5, 8, 12], dtype=int32),)
这与将0,1,2,3添加到位置相同:
In [195]: np.arange(n)+place
Out[195]: array([ 3, 5, 8, 12])
制作一个目标数组和掩码数组:
In [196]: out = np.zeros(len(cell)+n, dtype=cell.dtype)
In [197]: mask = np.ones(len(out), dtype=bool)
使用掩码来定义我们插入原始值的位置
In [198]: mask[Out[195]]=False
In [199]: out[mask] = cell
In [200]: out
Out[200]: array([1, 4, 4, 0, 5, 0, 5, 2, 0, 5, 1, 1, 0, 5])
由于插入值为0,我们不需要再做任何事情了。
我在上一个答案中建议concatenate 比插入更快,因为insert 更通用并且需要更多时间来设置。情况可能也是如此。但我预计时间不会有一点改善。
广义连接
In [235]: catlist = [cell[:place[0]],[0]]
In [236]: for i in range(n-1):
...: catlist.append(cell[place[i]:place[i+1]])
...: catlist.append([0])
...:
In [237]: catlist.append(cell[place[-1]:])
In [238]: np.concatenate(catlist)
Out[238]: array([1, 4, 4, 0, 5, 0, 5, 2, 0, 5, 1, 1, 0, 5])