从索引的列/行数组填充出现矩阵


问题内容

我正在寻找一种有效的方法,可以从两个包含索引的数组中创建出现矩阵,一个数组代表此矩阵中的 行索引 ,另一个代表 列索引

例如。我有:

#matrix will be size 4x3 in this example
#array of rows idxs, with values from 0 to 3
[0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3]
#array of columns idxs, with values from 0 to 2
[0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 2, 2, 2, 2]

并且需要创建一个发生矩阵,例如:

[[1  0  0]
 [0  2  0]
 [0  1  2]
 [2  1  5]]

我可以用一种简单的形式创建一个由一个热向量组成的数组,但是当出现多个事件时,它就无法工作:

n_rows    = 4
n_columns = 3
#data
rows    = np.array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3])
columns = np.array([0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 2, 2, 2, 2])
#empty matrix
new_matrix = np.zeros([n_rows, n_columns])
#adding 1 for each [row, column] occurrence:
new_matrix[rows, columns] += 1
print(new_matrix)

哪个返回:

[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  1.  1.]
 [ 1.  1.  1.]]

当出现多个索引/索引时,索引和添加这样的值似乎不起作用,除了打印外,它似乎还可以:

print(new_matrix[rows, :])

[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  1.  0.]
 [ 0.  1.  1.]
 [ 0.  1.  1.]
 [ 0.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

所以也许我在那里缺少什么?还是无法做到这一点,而我需要寻找另一种方法呢?


问题答案:

使用np.add.at,指定一个索引元组:

>>> 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就地对数组进行操作,向元组1指定的索引添加次数(row, columns)