[英]Select specific percentage of cells at random from numpy 2D array
I have foll. 我有福。 2D numpy array: 2D numpy数组:
array([[[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
...,
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768]]], dtype=int16)
with following unique values: 具有以下唯一值:
array([-32768, 401, 402, 403, 404], dtype=int16)
Is there a way I can create a new array where 10% of the cells with 401 are changed to 500? 有什么办法可以创建一个新数组,将401的单元格的10%更改为500? I can use np.random.random_sample()
to start but not how to select specified percentage of cells (eg 10% from this numpy 2D array) 我可以使用np.random.random_sample()
来启动,但不能如何选择指定百分比的单元格(例如,从该numpy 2D数组中选择10%)
Denote your array by a
. 表示你的阵列a
。 Then this will do the job: 然后,这将完成工作:
locs=np.vstack(np.where(a==401)).T
n=len(locs)
changes_loc=np.random.permutation(locs)[:n//10]
a[changes_loc[:,0],changes_loc[:,1]]=500
Here is a small example (with different numbers and 25% instead of 10%, just to depict the behavior): 这是一个小示例(用不同的数字和25%而不是10%来描述行为):
a=np.array([[1,2,3],[4,1,5],[1,1,7]])
locs=np.vstack(np.where(a==1)).T
n=len(locs)
changes_loc=np.random.permutation(locs)[:n//4]
a[changes_loc[:,0],changes_loc[:,1]]=70
the result is 结果是
array([[70, 2, 3],
[ 4, 1, 5],
[ 1, 1, 7]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.