Fill matrix of occurences from column/row arrays of indexes

后端 未结 2 722
后悔当初
后悔当初 2021-01-13 21:10

I\'m searching for an efficient way to create a matrix of occurrences from two arrays that contains indexes, one represents the row indexes in this matrix,

2条回答
  •  旧巷少年郎
    2021-01-13 21:44

    Use np.add.at, specifying a tuple of indices:

    >>> np.add.at(new_matrix, (rows, columns), 1)
    >>> new_matrix
    array([[ 1.,  0.,  0.],
           [ 0.,  2.,  0.],
           [ 0.,  1.,  2.],
           [ 2.,  1.,  5.]])
    

    np.add.at operates on the array in-place, adding 1 as many times to the indices as specified by the (row, columns) tuple.

提交回复
热议问题