我必须分析二次2D numpy数组LL的对称值(LL [i,j] == LL [j,i])而不是零。
是否有更快,更“数组”的方式没有循环来做到这一点? 是否有一种简单的方法来存储值的索引以供以后使用而无需创建数组并在每个循环中追加索引的元组?
这是我存储索引的经典循环方法:
IdxArray = np.array() # Array to store the indices
for i in range(len(LL)):
for j in range(i+1,len(LL)):
if LL[i,j] != 0.0:
if LL[i,j] == LL[j,i]:
IdxArray = np.vstack((IdxArray,[i,j]))
稍后使用指数:
for idx in IdxArray:
P = LL[idx]*(TT[idx[0]]-TT[idx[1]])
...
答案 0 :(得分:3)
>>> a = numpy.matrix('5 2; 5 4')
>>> b = numpy.matrix('1 2; 3 4')
>>> a.T == b.T
matrix([[False, False],
[ True, True]], dtype=bool)
>>> a == a.T
matrix([[ True, False],
[False, True]], dtype=bool)
>>> numpy.nonzero(a == a.T)
(matrix([[0, 1]]), matrix([[0, 1]]))
答案 1 :(得分:2)
这个怎么样:
a = np.array([[1,0,3,4],[0,5,4,6],[7,4,4,5],[3,4,5,6]])
np.fill_diagonal(a, 0) # changes original array, must be careful
overlap = (a == a.T) * a
indices = np.argwhere(overlap != 0)
结果:
>>> a
array([[0, 0, 3, 4],
[0, 0, 4, 6],
[7, 4, 0, 5],
[3, 4, 5, 0]])
>>> overlap
array([[0, 0, 0, 0],
[0, 0, 4, 0],
[0, 4, 0, 5],
[0, 0, 5, 0]])
>>> indices
array([[1, 2],
[2, 1],
[2, 3],
[3, 2]])