【问题标题】:Fast way to fill matrix from np.array of row index, column index, and max(values)从行索引、列索引和最大值(值)的 np.array 填充矩阵的快速方法
【发布时间】:2018-05-11 14:01:33
【问题描述】:

我有相当大的数组来填充矩阵(大约5e6 元素)。我知道快速填充的方法类似于

(简化示例)

bbb = (np.array([1,2,3,4,1])) # row
ccc = (np.array([0,1,2,1,0])) # column
ddd = (np.array([55.5,22.2,33.3,44.4,11.1])) # values

experiment = np.zeros(shape=(5,3))
experiment[bbb, ccc] = [ddd] # filling
>[[  0.    0.    0. ]
 [ 11.1   0.    0. ]
 [  0.   22.2   0. ]
 [  0.    0.   33.3]
 [  0.   44.4   0. ]]

但如果我想要最大的ddd。类似于# filling

#pseudocode
experiment[bbb, ccc] = [ddd if ddd > experiment[bbb, ccc]]

矩阵应该返回

>[[  0.    0.    0. ]
 [ 55.5   0.    0. ]
 [  0.   22.2   0. ]
 [  0.    0.   33.3]
 [  0.   44.4   0. ]]

这里有什么好的快速方法可以从 np.array 中获取 max 来填充矩阵?

【问题讨论】:

  • 我不明白你在做什么。你是如何得出最后一个矩阵的?

标签: python arrays python-2.7 numpy matrix


【解决方案1】:

您可以在np.maximum 上使用np.ufunc.at

np.ufunc.at 执行前面的ufunc“无缓冲和就地”。这意味着出现在[bbb, ccc] 中的所有索引都将由np.maximum 处理,无论这些索引多久出现一次。

在您的情况下,(0, 1) 出现两次,因此将被处理两次,每次选择 experiment[bbb, ccc]ddd 的最大值。

np.maximum.at(experiment, [bbb, ccc], ddd)
# array([[  0. ,   0. ,   0. ],
#        [ 55.5,   0. ,   0. ],
#        [  0. ,  22.2,   0. ],
#        [  0. ,   0. ,  33.3],
#        [  0. ,  44.4,   0. ]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2017-02-22
    • 2013-12-25
    相关资源
    最近更新 更多