受其他数组限制的Numpy随机数组

2024-05-17 12:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个同样大小的婴儿床。你知道吗

a = np.random.randn(x,y)
b = np.random.randn(x,y)

我想创建一个新数组,其中每个元素都是ab中具有相同索引的元素值之间的随机值。所以每个元素c[i][j]应该在a[i][j]b[i][j]之间。 有没有比遍历c的所有元素并分配随机值更快/更简单/更有效的方法?你知道吗


Tags: 方法元素nprandom数组randn婴儿床
3条回答

你可以这样做:

c=a+(b-a)*d

其中d=值介于0和1之间的随机数组,其维数与

您可以使用文档中的numpy.random.uniform

low : float or array_like of floats, optional

Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

high : float or array_like of floats

Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.

因此lowhigh都可以接收数组作为参数,为了完整性,请参见下面的代码:

代码:

import numpy as np

x, y = 5, 5

a = np.random.randn(x, y)
b = np.random.randn(x, y)

high = np.maximum(a, b)
low = np.minimum(a, b)

c = np.random.uniform(low, high, (x, y))

print((low <= c).all() and (c <= high).all())

输出

True

在上面的例子中,注意使用maximumminimum来构建highlow。最后一行检查c的所有值是否都在highlow之间。如果您感兴趣,您可以在一行中完成这一切:

c = np.random.uniform(np.minimum(a, b), np.maximum(a, b), (x, y))

下面是一个使用numpy的想法:

a = np.random.randn(2,5)
array([[ 1.56068748, -2.21431346],
       [-0.33707115,  0.93420256]])

b = np.random.randn(2,5)
array([[-0.0522846 ,  0.11635731],
       [-0.57028069, -1.08307492]])

# Create an interleaved array from both a and b 
s = np.vstack((a.ravel(),b.ravel()))

array([[ 1.56068748, -2.21431346, -0.33707115,  0.93420256],
       [-0.0522846 ,  0.11635731, -0.57028069, -1.08307492]])

# Feed it to `np.random.uniform` which takes low and high as inputs 
# and reshape it to match input shape
np.random.uniform(*s).reshape(a.shape)

array([[ 0.14467235, -0.79804187],
       [-0.41495614, -0.19177284]])

相关问题 更多 >