0

Hi there I have an np array with zeros and ones. I would like to check every 4 values, and if there is at least one (1) to put all four values equal to (1). Else leave all them to zero.

do you know how to do it? thanks here is a sample

np= [ 0 0 0 0 1 1 1 1 0 0 1 0 0 0 0 0 ]

np_corrected=np= [ 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 ]

many thanks, hope the question is now clear!

teratoulis
  • 57
  • 5

1 Answers1

0

Probably not the shortest solution but definitely working and fast:

  1. reshape
  2. create a mask
  3. apply the mask and get the result:
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

Returns (in Jupyter notebook):

array([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0])
array([[0, 0, 0, 0],
       [1, 1, 1, 1],
       [0, 0, 1, 0],
       [0, 0, 0, 0]])
array([False,  True,  True, False])
array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0])
isCzech
  • 313
  • 1
  • 1
  • 7