python - 用另一个数组中的随机元素填充 numpy 数组

标签 python numpy

我不确定这是否可行,但可以。假设我有一个数组:

array1 = [0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]

现在我想创建一个由 5 个元素组成的 numpy 一维数组,这些元素是从 array1 中随机抽取的,条件是总和等于 1。示例类似于一个 numpy 数组,看起来像 [.2,.2,.2,.1,.1]

  • 目前我使用随机模块,选择函数如下所示: range1= np.array([choice(array1),choice(array1),choice(array1),choice(array1),choice(array1)]) 然后检查 range1 是否符合标准;我想知道是否有更快的方法,类似于 randomArray = np.random.random() 代替。

  • 如果我可以将这个数组存储在某个库中,那就更好了,这样如果我尝试生成 100 个这样的数组,就没有重复,但这不是必需的。

最佳答案

您可以使用 numpy.random.choice如果你使用 numpy 1.7.0+:

>>> import numpy as np
>>> array1 = np.array([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
>>> np.random.choice(array1, 5)
array([ 0. ,  0. ,  0.3,  1. ,  0.3])
>>> np.random.choice(array1, 5, replace=False)
array([ 0.6,  0.8,  0.1,  0. ,  0.4])

求和等于1的5个元素,

  • 生成 4 个随机数。
  • 从 1 -> x 中减去 4 个数的和
  • 如果 x 包含在 array1 中,则使用它作为最终数字;或重复

>>> import numpy as np
>>> 
>>> def solve(arr, total, n):
...     while True:
...         xs = np.random.choice(arr, n-1)
...         remain = total - xs.sum()
...         if remain in arr:
...             return np.append(xs, remain)
... 
>>> array1 = np.array([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
>>> print solve(array1, 1, 5)
[ 0.1  0.3  0.4  0.2  0. ]

另一个版本(假设给定数组已排序):

EPS = 0.0000001
def solve(arr, total, n):
    while True:
        xs = np.random.choice(arr, n-1)
        t = xs.sum()
        i = arr.searchsorted(total - t)
        if abs(t + arr[i] - total) < EPS:
            return np.append(xs, arr[i])

关于python - 用另一个数组中的随机元素填充 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691142/

相关文章:

python - 合并字典而不覆盖值

python - 在 Pygame 中缩放图像/矩形

python - 用 Python 重写 Mathematica 输出

python - python bisect 比 numpy.searchsorted 快吗?

python - 如何使用 `watch` 使用特定于 bash 的语法?

python - 如何为 Keras 准备数据集?

python - 获取与同一个表中的父元素相关的子元素

python matplotlib 绘制稀疏矩阵模式

python - 从查找表返回索引,允许空值且未找到

python - 如何将 `numpy.datetime64` 列表转换为 `matplotlib.dates` ?