问题
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 array myArray2
based on myArray1
. Where myArray1
has a value of 1, I want to replace the value by numpy.random.normal(loc=40, scale=10)
.
How can I do that?
回答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
.
回答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.
来源:https://stackoverflow.com/questions/22556640/replace-value-in-array-with-numpy-random-normal