Frage

I have to analyze a quadratic 2D numpy array LL for values which are symmetric (LL[i,j] == LL[j,i]) and not zero.

Is there a faster and more "array like" way without loops to do this? Is there a easy way to store the indices of the values for later use without creating a array and append the tuple of the indices in every loop?

Here my classical looping approach to store the indices:

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]))                    

later use the indices:

for idx in IdxArray:
    P = LL[idx]*(TT[idx[0]]-TT[idx[1]])
    ...
War es hilfreich?

Lösung 2

How about this:

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)

Result:

>>> 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]])

Andere Tipps

>>> 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]]))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top