3

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.

2
  • 2
    You need to show what you have done before you ask a question. If you have no idea where to begin, here is a hint: read the data into a dictionary with the 'A & A' etc as the keys and then sort the dictioanry with the sorted() function using the key parameter. Commented Feb 21, 2014 at 0:58
  • edited what i have so far Commented Feb 21, 2014 at 1:05

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

awesome. how would i go about pulling out the fact that 0.51 corresponds to "B&C"?
He wants the output he provided. :)
1

Starting from a numpy array, like this:

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

you can do like this:

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)

OUTPUT:

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

3 Comments

Receiving an error: for k,v in values: ValueError:too many values to unpack
how would i go about taking the output and saving it into a csv file
@user3334418 csv module docs and the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.