Home > OS >  update Numpy Array element if there is a True in the whole row
update Numpy Array element if there is a True in the whole row

Time:10-15

I have a very large numpy array with True/False that has the shape of (500000, 36), here I put a sample array for this question:


mask_array = [[False, False, False, False .., False],
              [False, True, False, False ..., False]]

For each row of the numpy array, I want to check if there is any element that is True, and if there is, set the last element of the row equal to True.

This is my sample code:


def update_array(x):
    if x.any():
       x[-1] == True

np.apply_along_axis(update_array, axis=1, arr=mask)

Expected results:

mask_array = [[False, False, False, False .., False],
              [False, True, False, False ..., True]]



CodePudding user response:

You can do it using any with specified axis and then assing result to last elements of array's rows.

Sample code:

mask_array = np.array([[False, False, False, False , False],
                       [False, True, False, False , False]])

mask_array[:,-1] = mask_array.any(axis=1)

Result:

array([[False, False, False, False, False],
       [False,  True, False, False,  True]])
  • Related