Replace value in array with numpy.random.normal

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 05:37:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!