Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Replace random elements in an array

I already googled a bit and didn't find any good answers.

The thing is, I have a 2d numpy array and I'd like to replace some of its values at random positions.

I found some answers using numpy.random.choice to create a mask for the array. Unfortunately this does not create a view on the original array so I can not replace its values.

So here is an example of what I'd like to do.

Imagine I have 2d array with float values.

[[ 1., 2., 3.],
 [ 4., 5., 6.],
 [ 7., 8., 9.]]

And then I'd like to replace an arbitrary amount of elements. It would be nice if I could tune with a parameter how many elements are going to be replaced. A possible result could look like this:

[[ 3.234, 2., 3.],
 [ 4., 5., 6.],
 [ 7., 8., 2.234]]

I couldn't think of nice way to accomplish this. Help is appreciated.

like image 867
Nima Mousavi Avatar asked Jul 13 '15 17:07

Nima Mousavi


People also ask

How do you select a random element from a NumPy array?

choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python. Parameters: a: a one-dimensional array/list (random sample will be generated from its elements) or an integer (random samples will be generated in the range of this integer)

What is random rand () function in NumPy?

The numpy.random.rand() function creates an array of specified shape and fills it with random values. Syntax : numpy.random.rand(d0, d1, ..., dn) Parameters : d0, d1, ..., dn : [int, optional]Dimension of the returned array we require, If no argument is given a single Python float is returned.

What does NP random choice do?

Definition of NumPy random choice. The NumPy random choice() function is used to gets the random samples of a one-dimensional array which returns as the random samples of NumPy array. The NumPy random choice() function is a built-in function in the NumPy package of python.

What is replace in NumPy?

replace() function of the char module in Numpy library. The replace() function is used to return a copy of the array of strings or the string, with all occurrences of the old substring replaced by the new substring.


1 Answers

Just mask your input array with a random one of the same shape.

import numpy as np

# input array
x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]])

# random boolean mask for which values will be changed
mask = np.random.randint(0,2,size=x.shape).astype(np.bool)

# random matrix the same shape of your data
r = np.random.rand(*x.shape)*np.max(x)

# use your mask to replace values in your input array
x[mask] = r[mask]

Produces something like this:

[[ 1.          2.          3.        ]
 [ 4.          5.          8.54749399]
 [ 7.57749917  8.          4.22590641]]
like image 117
derricw Avatar answered Sep 23 '22 22:09

derricw