【问题标题】:Numpy random array limited by other arrays受其他数组限制的 Numpy 随机数组
【发布时间】:2019-06-27 11:37:41
【问题描述】:

我有两个大小相同的 numpy ndarray。

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

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

【问题讨论】:

    标签: python arrays python-3.x numpy numpy-ndarray


    【解决方案1】:

    你可以这样做:

    c=a+(b-a)*d
    

    其中 d = 值介于 0 和 1 之间且与 a 相同的维度的随机数组

    【讨论】:

      【解决方案2】:

      这是一个使用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]])
      

      【讨论】:

        【解决方案3】:

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

        low : float 或 array_like 的浮点数,可选

        输出区间的下边界。生成的所有值将是 大于或等于低。默认值为 0。

        high : float 或 array_like 的浮点数

        输出区间的上边界。生成的所有值将是 低于高。默认值为 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))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-05
          • 1970-01-01
          • 2013-09-26
          相关资源
          最近更新 更多