3

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?

2
  • Will the shapes always be a match? So will arra_b.size always equal the number of True in arr_a? Commented Jun 26, 2019 at 16:13
  • Yes, the shapes will always be a match Commented Jun 26, 2019 at 16:27

3 Answers 3

2

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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Here is what this returned: >>> arr_a = np.array([[0, 0, 0], [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) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot reshape array of size 6 into shape (3,)
I just ran it again and it works without an error. Check the edit to my answer to see if my arrays a and b are equal to yours
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.