我正在尝试更新 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 有多种方法。 plonser
对 product
的使用有效,尽管我很少看到它与 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/