Python ProgrammingPython Programming

How to Calculate correlation between two DataFrame objects in Pandas?

Calculating correlation between two DataFrame:

import pandas as pd

df1 = pd.DataFrame([[10, 20, 30, 40], [7, 14, 21, 28], [55, 15, 8, 12],
                   [15, 14, 1, 8], [7, 1, 1, 8], [5, 4, 9, 2]],
                  columns=['Apple', 'Orange', 'Banana', 'Pear'],
                  index=['Basket1', 'Basket2', 'Basket3', 'Basket4',
                         'Basket5', 'Basket6'])

print("\n------ Calculating Correlation of one DataFrame Columns -----\n")
print(df1.corr())

df2 = pd.DataFrame([[52, 54, 58, 41], [14, 24, 51, 78], [55, 15, 8, 12],
                   [15, 14, 1, 8], [7, 17, 18, 98], [15, 34, 29, 52]],
                  columns=['Apple', 'Orange', 'Banana', 'Pear'],
                  index=['Basket1', 'Basket2', 'Basket3', 'Basket4',
                         'Basket5', 'Basket6'])

print("\n----- Calculating correlation between two DataFrame -------\n")
print(df2.corrwith(other=df1))


C:\pandas>python example.py
 
------ Calculating Correlation of one DataFrame Columns -----
 
           Apple    Orange    Banana      Pear
Apple   1.000000  0.341959 -0.180874 -0.125364
Orange  0.341959  1.000000  0.646122  0.737144
Banana -0.180874  0.646122  1.000000  0.918606
Pear   -0.125364  0.737144  0.918606  1.000000
 
----- Calculating correlation between two DataFrame -------
 
Apple     0.678775
Orange    0.354993
Banana    0.920872
Pear      0.076919
dtype: float64
 
C:\pandas>