Professional Documents
Culture Documents
How To Create A Correlation Matrix Using Pandas - Data To Fish
How To Create A Correlation Matrix Using Pandas - Data To Fish
datatofish.com/correlation-matrix-pandas
In this short guide, I’ll show you how to create a Correlation Matrix using Pandas. I’ll also
review the steps to display the matrix using Seaborn and Matplotlib.
To start, here is a template that you can apply in order to create a correlation matrix using
pandas:
df.corr()
A B C
45 38 10
37 31 15
42 26 17
35 28 21
39 33 12
import pandas as pd
df = pd.DataFrame(data,columns=['A','B','C'])
print (df)
Once you run the code, you’ll get the following DataFrame:
Step 3: Create a Correlation Matrix using Pandas
Now, create a correlation matrix using this template:
df.corr()
This is the complete Python code that you can use to create the correlation matrix for our
example:
import pandas as pd
df = pd.DataFrame(data,columns=['A','B','C'])
corrMatrix = df.corr()
print (corrMatrix)
Run the code in Python, and you’ll get the following matrix:
import seaborn as sn
import matplotlib.pyplot as plt
sn.heatmap(corrMatrix, annot=True)
plt.show()
So the complete Python code would look like this:
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
df = pd.DataFrame(data,columns=['A','B','C'])
corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True)
plt.show()
Run the code, and you’ll get the following correlation matrix: