Replace Value In Array With Numpy.random.normal
I have the following array: myArray1 = np.array([[255, 255, 255, 1, 1, 255, 255, 255], [255, 1, 1, 1, 1, 1, 255, 255]]) I want to create a new a
Solution 1:
If your array is called a
, you can do
b = a == 1
a[b] = numpy.random.normal(loc=40, scale=10, size=b.sum())
This avoids Python loops and takes advantage of Numpy's performance.
The first line creates a Boolean array with the same shape as a
that is True
in all entries that correspond to ones in a
. The second line uses advanced indexing with this Boolean array to assign new values only to the places where b
is True
.
Solution 2:
How about a list comprehension like this:
[i if i != 1 else numpy.random.normal(loc=40, scale=10) for j in myArray1 for i in j]
j
loops through each of the rows of myArray1
and i
loops through each element of the row.
Post a Comment for "Replace Value In Array With Numpy.random.normal"