Jalb
Jalb

Reputation: 13

Turning a matrix into a table

I created a matrix of Spearman correlation values using

pd.DataFrame.corr

Now I´m trying to turn this matrix into a table with the columns X-Value, Y-Value and Spearman correlation coefficient. So that I can rank it by the highest coefficients.

Can anyone help me transform the matrix into the 3 column table?

Thank You!

Upvotes: 1

Views: 246

Answers (1)

jcaliz
jcaliz

Reputation: 4021

Try:

df.corr(method='spearman').stack().to_frame(name='correlation')

A more sophisticated way that also deletes duplicates is:

correlations = df.corr(method='spearman')

correlation_table = (
    correlations.where(
        np.triu(np.ones(correlations.shape), k=0)
        .astype(bool)
    )
    .stack()
    .to_frame(name='correlation')
)

Upvotes: 1

Related Questions