python - Numpy 矩阵的综合索引更新

标签 python numpy matrix

我正在尝试更新 numpy 矩阵的一组特定行和列。这是一个例子:

import numpy as np
A=np.zeros((8,8))
rows=[0, 1, 5]
columns=[2, 3]
#(What I am trying to achieve) The following does not update A
A[rows][:,columns]+=1
#while this just does
for i in rows:
    A[i][columns]+=1

我期望的输出是:

In [1]:print(A)
Out[1]: 
    array([[ 0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

有没有办法在不循环的情况下同时执行多列和多行更新?

最佳答案

rows 需要是“列”向量,例如

rows=[[0],[1],[5]]
cols=[2,3]
A[rows,cols]+=1

有时 2 阶段索引工作,A[rows][:,cols],但并非总是如此。特别是在 rows 不是切片的情况下。 A[rows] 现在是一个副本,因此更改它不会更改 A

索引这个 block 有多种方法。 plonserproduct 的使用有效,尽管我很少看到它与 numpy 一起使用。

np.ix_ 是执行此操作的便捷工具:

In [70]: np.ix_([0,1,5],[2,3])
Out[70]: 
(array([[0],
        [1],
        [5]]), array([[2, 3]]))

np.newaxis 还将行向量转换为列向量:

rows=np.array([0,1,5])
cols=np.array([2,3])
A[rows[:,None],cols]

这对列向量和行向量之所以有效,是因为 numpy 广播它们以生成 (3,2) 索引数组。

itertools.product 生成相同的索引集,但作为元组列表(或生成器)

In [80]: list(itertools.product([0,1,5],[2,3]))
Out[80]: [(0, 2), (0, 3), (1, 2), (1, 3), (5, 2), (5, 3)]
In [84]: tuple(np.array(list(itertools.product([0,1,5],[2,3]))).T)
Out[84]: (array([0, 0, 1, 1, 5, 5]), array([2, 3, 2, 3, 2, 3]))

关于python - Numpy 矩阵的综合索引更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29519050/

相关文章:

python - 基本 Numpy 数组值赋值

python - 了解如何为 numpy reshape() 指定新的形状参数

R最大化矩阵列表

python - 在python中生成具有加权概率的随机数

python - 是否可以部署使用 Python 3.4 和 Fabric 的应用程序?

python - GraphKeys.TRAINABLE_VARIABLES 与 tf.trainable_variables()

r - 用两个分隔符连接矩阵行

python - pyth 错误 [rtf 到 xml/html]

python - 向量化 python 代码以提高性能

c++ - 为什么 Strassen 矩阵乘法比标准矩阵乘法慢得多?