Reputation: 322
I compute correlation coefficient like this (its just example):
a = np.array([[1, 2, 3],
[4, 7, 9],
[8, 7, 5]])
corr = np.corrcoef(a)
The result is a correlation matrix.
The question is how to get 1st, 2nd (or nth) largest coefficient?
And its index? like [0,1]
and [2,1]
Upvotes: 1
Views: 1143
Reputation: 1731
Let's say you have a NumPy array and you computed the correlation coefficient like this:
import numpy as np
a = np.array([[1, 2, 3],
[4, 7, 9],
[8, 7, 5]])
corr = np.corrcoef(a)
Now flatten the array, take the unique coefficients and sort the flattened array:
flat=corr.flatten()
flat = np.unique(flat)
The flat array looks like this:
>> array([-0.98198051, -0.95382097, 0.99339927, 1. ])
Now to pick nth largest
element, just pick the right index:
largest = flat[-1]
second_largest = flat[-2]
print(largest)
print(second_largest)
>> 1.0
>> 0.9933992677987828
To find the indices of the corresponding coefficient:
result = np.where(corr == largest)
indices = np.array(result)
print(indices)
This prints out the following array. So the indices where the largest coefficient occurs are (0,0), (1,1) and (2,2).
>> array([[0, 1, 2],
[0, 1, 2]])
Upvotes: 3