What I have so far is:
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 dont have the column names or the 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 the output I would like is:
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 would like to save it into a csv file where the first column are the names and the second column are the corresponding scores
Thanks for reading.
Call np.sort with the axis keyword argument set to None, then reverse it with 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 is coming from, then first use np.argsort, then unravel the flattened indices:
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With