简体   繁体   中英

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 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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM