Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create relative entropy matrix from pandas dataframe

I have a dataframe of values, say:

df = pd.DataFrame(np.array([[0.2, 0.5, 0.3], [0.1, 0.2, 0.5], [0.4, 0.3, 0.3]]),
                   columns=['a', 'b', 'c'])

in which every row is a vector of probabilities. I want to compute something like the correlation matrix of df.corr() , but instead of correlation, I want to compute the relative entropy.

What is the best way to do this, as I can’t find a way to get inside the .corr() method and simply change the function it uses?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

IIUC, use .corr as follows:

import pandas as pd
import numpy as np

from scipy.stats import entropy

df = pd.DataFrame(np.array([[0.2, 0.5, 0.3], [0.1, 0.2, 0.5], [0.4, 0.3, 0.3]]),
                   columns=['a', 'b', 'c'])

res = df.corr(method=entropy)
print(res)

Output

          a         b         c
a  1.000000  0.160246  0.270608
b  0.160246  1.000000  0.167465
c  0.270608  0.167465  1.000000

From the documentation:

callable:
callable with input two 1d ndarrays and returning a float.
Note that the returned matrix from corr will have 1 along the
diagonals and will be symmetric regardless of the callable’s behavior.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading