我有一个数组,我用0到1的随机浮点数填充。
x = np.random.random((20,20))
稍后,我将提取数组(x [row] [column])中大于0.2的项目,其中包含:
loc = np.argwhere(x > 0.2)
但是,我无法控制loc
的大小。我必须有最多80个元素才能提供大于0.2的条件。
maxnum = 80
len(loc) == maxnum
每次提供大于0.2的项目的[row][column]
组合应该是不同的,因为它应该是随机数组。
更具体地说,如果我要制作一个数组:
y = np.random.random((4,4))
产生:
array([[ 0.90282391, 0.11295454, 0.22650744, 0.31376307],
[ 0.44553798, 0.19264588, 0.8944689 , 0.77730786],
[ 0.17462983, 0.79806749, 0.02074193, 0.3545992 ],
[ 0.60130149, 0.5982725 , 0.20522246, 0.99080217]])
我只需要随机3个大于0.2。 因此,预期输出应如下所示:
array([[ **0.90282391**, 0.11295454, 0.12650744, 0.11376307],
[ 0.14553798, 0.19264588, 0.1944689 , 0.17730786],
[ 0.17462983, 0.19806749, 0.02074193, **0.3545992** ],
[ 0.10130149, **0.5982725** , 0.10522246, 0.19080217]])
和粗体(大于0.2)它们的位置应该在每次运行时都会改变。
你知道如何实现这个输出吗?
答案 0 :(得分:1)
import numpy as np
n = 20
threshold = 0.2
maxNum = 80
res = np.zeros([n, n])
perm = np.random.permutation(n ** 2)
res.flat[perm[:maxNum]] = np.random.uniform(size=maxNum, low=threshold, high=1)
res.flat[perm[maxNum:]] = np.random.uniform(size=n**2 - maxNum, low=0, high=threshold)
让我解释一下。我们创建一个形状为res
的空数组(n, n)
。我们的maxNum
值确切地高于threshold
。
我们在0和n ** 2 - 1之间选择maxNum
个不同的索引(我使用np.random.permutation
)。我们在res
的展平视图中填充相应的值,其中均匀值介于0.2和1之间。
我们在res
的其余部分填充统一绘制在0和0.2之间的值。
所以:
In [59]: len(np.argwhere(res > threshold))
Out[59]: 80
答案 1 :(得分:-1)
这会有所帮助
l=np.random.random((20,20))
loc= np.argwhere(l>.2) if len(np.argwhere(l>.2))<=80 else np.argwhere(l>.2)[:80]
如果数据丢失,那么