import numpy as np
array = np.array([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0])
array
groups = array.reshape(-1, 4) # group every 4 elements into new columns
groups
mask = groups.sum(axis=1)>0 # identify groups with at least one '1'
mask
np.logical_or(groups.T, mask).T.astype(int).flatten()
# swap rows and columns in groups, apply mask, swap back,
# replace True/False with 1/0 and restore original shape
1条答案
按热度按时间ctehm74n1#
可能不是最短的解决方案,但绝对有效且快速:
1.整形
1.创建遮罩
1.应用遮罩并获得结果:
返回(在Jupyter笔记本中):