Sort matrix values ​​in python

What I still have:

dict={'A':[1,2,3], 'B':[2,5,4], 'C':[2,1,8]}
N=len(keys)
m=numpy.zeros(N,N)
for i in range(N):
    for j in range(N):
         m[i-1,j-1]=covariance(values[i-1],values[j-1])
         m[j-1,i-1]=covariance(values[j-1],values[i-1])
m=numpy.triu(m)

which gives me:

1   0.639  0.07
0     1    0.51
0     0      1

I don't have column names or row names yet. I would like something like this:

       A     B      C
A      1   0.639  0.07
B      0     1    0.51
C      0     0      1

Given this matrix, I would like to sort it in descending order by the value of the matrix, so I would like to:

A & A: 1
B & B: 1
C & C: 1
A & B: 0.639
B & C: 0.51
A & C: 0.07
B & A: 0 #etc

From the output, I would like to save it to a csv file, where the first column is the names, and the second column is the corresponding estimates

Thanks for reading.

+3
source share
2 answers

Call np.sortwith the keyword argument axisset to None, then cancel it by slicing:

>>> a = np.array([[1, 0.639, 0.07], [0, 1, 0.51], [0, 0, 1]])
>>> a
array([[ 1.   ,  0.639,  0.07 ],
       [ 0.   ,  1.   ,  0.51 ],
       [ 0.   ,  0.   ,  1.   ]])
>>> np.sort(a, axis=None)[::-1]
array([ 1.   ,  1.   ,  1.   ,  0.639,  0.51 ,  0.07 ,  0.   ,  0.   ,  0.   ])

If you want to know where each value comes from, first use np.argsort, then guess the smoothed indexes:

>>> idx = np.argsort(a, axis=None)[::-1]
>>> rows, cols = np.unravel_index(idx, a.shape)
>>> a_sorted = a[rows, cols]
>>> for r, c, v in zip(rows, cols, a_sorted):
...     print 'ABC'[r], '&', 'ABC'[c], ':', v
... 
C & C : 1.0
B & B : 1.0
A & A : 1.0
A & B : 0.639
B & C : 0.51
A & C : 0.07
C & B : 0.0
C & A : 0.0
B & A : 0.0
+2

numpy, :

matrix = numpy.array( [ [ 1, 0.639, 0.07 ],
                        [ 0, 1,     0.51 ],
                        [ 0, 0,     1 ]  ] )

:

indices = ["A", "B", "C", ]                     

values = []

for r,row in enumerate( matrix ):
    for c, cell in enumerate( row ):
        values.append( ("{} & {}".format( indices[r], indices[c] ), cell ) )

values.sort( key=lambda it: (-it[1], it[0]) )

for k,v in values:
    print "{}: {}".format(k,v)

:

A & A: 1.0
B & B: 1.0
C & C: 1.0
A & B: 0.639
B & C: 0.51
A & C: 0.07
B & A: 0.0
C & A: 0.0
C & B: 0.0
+1

All Articles