Mixing Two Numpy Arrays Randomly

1.3k Views Asked by At

This is my first question on Stack Overflow, so bear with me. Let's say I have two arrays of the same shape, X and Y

import numpy as np

X = np.array(([0, 0],
              [0, 0]), dtype=float)

X = np.array(([1, 1],
              [1, 1]), dtype=float)

I want to create a function mix_arrays(X, Y) that will mix the arrays together randomly, like so:

def mix_arrays(array_0, array_1)
    # magic
    new_array =  # ...
    return new_array

Here's what it could return:

mix_arrays(X, Y)
# Could Return:
# [[0, 1], 
#  [1, 1]]
# or:
# [[1, 0], 
#  [0, 1]]
# or:
# [[0, 0], 
#  [1, 1]]

Basically, the for each element in new_array, the element has a 50% chance being from array_0, and a 50% chance being from array_1

I'm sure this question already exists, but I couldn't find it on stack overflow. Thank you in advance for your time!

1

There are 1 best solutions below

0
On

Just use np.where

def random_mix(X, Y):
    choice = np.random.randint(2, size = X.size).reshape(X.shape).astype(bool)
    return np.where(choice, X, Y)