AP_98
AP_98

Reputation: 29

Performing a random addition between two arrays

What I'm trying to do is get two different arrays, where the first array is just filled with zeros and second array would be populated by random numbers. I would like to perform an operation where only certain elements from the latter array are added to the array filled with zeros and the rest of elements within the former array remain as zero. I'm trying to get the addition done in a random way as well. I just added the code below as an example. I honestly don't know how to perform something like this and I would be very grateful for any help or suggestions! Thank you!

shape = (6, 3)
empty_array = np.zeros(shape)
random_array = 0.1 * np.random.randn(*empty_array)

sum = np.add(empty_array, random_array)

Upvotes: 1

Views: 301

Answers (2)

Ehsan
Ehsan

Reputation: 12407

If I understand you correctly from your comments, you want to create random numbers at random indices based on the threshold of some percent of whole array (you do not need to create a whole random array and use only a percent of it, such random number generation is usually costly in larger scales):

sz = shape[0]*shape[1]
#this is your for example 20% threshold
threshold = 0.2
#create random numbers and random indices
random_array = np.random.rand(int(threshold*sz))
random_idx = np.random.randint(0,sz,int(threshold*sz))

#now you can add this random_array to random indices of your desired array
empty_array.reshape(-1)[random_idx] += random_array

or another solution:

sz = shape[0]*shape[1]
#this is your for example 20% threshold
threshold = 0.2
random_array = np.random.rand(int(threshold*sz))
#pad with enough zeros and randomly shuffle and finally reshape it
random_array.resize(sz)
np.random.shuffle(random_array)

#now you can add this random_array to any array of your choice
empty_array += random_array.reshape(shape)

sample output:

[[0.         0.         0.        ]
 [0.         0.         0.        ]
 [0.         0.         0.7397274 ]
 [0.         0.         0.        ]
 [0.         0.         0.79541551]
 [0.75684113 0.         0.        ]]

Upvotes: 0

DYZ
DYZ

Reputation: 57033

You can use a binary mask with the density P:

P = 0.5
# Repeat the next two lines as needed
mask = np.random.binomial(1, P, size = empty_array.size)\
         .reshape(shape).astype(bool)
empty_array[mask] += random_array[mask]

If you plan to add more random elements, you may want to re-generate the mask at each further iteration.

Upvotes: 2

Related Questions