Preethi Vaidyanathan
Preethi Vaidyanathan

Reputation: 1322

How to use a numpy boolean array to modify another numpy array?

I have a boolean array that looks like this:

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

and another array that looks like this:

arr_b = np.array(
[[100, 100, 100],
[200, 200, 200]]
)

I am looking for a function that I can call like this: np.boolean_combine(arr_a, arr_b), to return an array that will replace the 1's in arr_a with the values from arr_b, for an end result that looks like this:

np.array(
[[0, 0, 0]
[100, 100, 100],
[200, 200, 200],
[0, 0, 0]]
)

Is there such a function?

Upvotes: 3

Views: 1326

Answers (3)

Kamuish
Kamuish

Reputation: 118

If your arr_a is made of 1's and 0's:

import numpy as np 
arr_a = np.array(
[[0, 0, 0],
[1, 1, 1],
[1, 1, 1],
[0, 0, 0]])
arra_b = np.array(

[[100, 100, 100],

[200, 200, 200]])


arr_a[np.where(arr_a)]  = arra_b.reshape(arr_a[np.where(arr_a)].shape)

This works, assuming that the shapes are a match

Upvotes: 1

mao95
mao95

Reputation: 1122

You can use zip(). Supposing that arr_a and arr_b are (obviously, from your problem) of the same dimension:

def boolean_combine(arr_a, arr_b) -> np.array:
  combined = []
  for row_a, row_b in zip(arr_a, arr_b):
    row_combined = []
    for a, b in zip(row_a, row_b):
      if a == 'True':
        row_combined.append(b)
      else:
        row_combined.append(a)
    combined.append(np.asarray(row_combined))
  return np.asarray(combined)

Then, you can call this function in your main just by typing combined = boolean_combine(arr_a, arr_b)

Upvotes: 0

yatu
yatu

Reputation: 88226

You can create a new array of the same dtype as arra_b, take a slice view using arr_a an assign the values from arra_b:

out = arr_a.astype(arra_b.dtype)
out[arr_a] = arra_b.ravel()

array([[  0,   0,   0],
       [100, 100, 100],
       [200, 200, 200],
       [  0,   0,   0]])

Upvotes: 2

Related Questions