【问题标题】:Numpy assign columns of a 2d array as sum of columns of indices of another arrayNumpy 将二维数组的列分配为另一个数组的索引列的总和
【发布时间】:2018-08-01 23:18:21
【问题描述】:

我想将一个二维数组的列表示为另一个矩阵的列子集的总和。什么是最有效的方法?。

现在,我所做的是,

for i in xrange(U.shape[1])
    U[:,i] = X[:,np.random.choice(X.shape[1], 10)].sum(axis=1)/10.0;

有没有更快更好的非循环方法?

【问题讨论】:

    标签: python arrays python-2.7 numpy vectorization


    【解决方案1】:

    一次性生成所有索引,索引到输入的 2D 数组给我们一个 3D 数组,最后沿最后一个轴求和 axis=2,就像这样 -

    indx = np.random.randint(0,X.shape[1], (U.shape[1],10))
    Uout = X[:,indx].sum(axis=2)/10.0
    

    如果你想用np.random.choice得到indx-

    np.random.choice(X.shape[1], size=(U.shape[1],10))
    

    使用np.take 索引对于大型数组来说似乎更快 -

    In [63]: X = np.random.rand(1000,1000)
    
    In [64]: indx = np.random.randint(0,1000, (1000,10))
    
    In [67]: %timeit X[:,indx]
    10 loops, best of 3: 69.9 ms per loop
    
    In [68]: %timeit np.take(X, indx, axis=1)
    10 loops, best of 3: 22.9 ms per loop
    

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 2022-12-31
      • 2018-04-11
      • 1970-01-01
      • 2020-10-25
      • 2021-03-03
      • 2019-05-22
      • 2019-05-05
      相关资源
      最近更新 更多