import random
import numpy
X = [random.randint(1, 100) for i in range(10)]
Y = [random.randint(1, 100) for i in range(10)]
print("X: ", X)
print("Y: ", Y)
corr_matrix = numpy.corrcoef(X, Y)
print("Correlation Matrix: \n", corr_matrix)
Here, we are generating 10 random integers for X and another 10 random integers for Y. After that, we are using the corrcoef() function from the numpy module to calculate the correlation matrix.
The output of the above program will be like the following:
X: [68, 7, 58, 22, 72, 84, 59, 39, 75, 49] Y: [30, 72, 22, 84, 87, 7, 57, 62, 74, 62] Correlation Matrix: [[ 1. -0.46866573] [-0.46866573 1. ]]
How to calculate the correlation matrix using the pandas Python library?
We can use the DataFrame.corr() function from the pandas Python library to calculate the correlation matrix.
import pandas
import seaborn
dataset = seaborn.load_dataset("tips")
print(dataset.head())
data = pandas.DataFrame(dataset[["total_bill", "tip"]])
print(data.head())
corr_matrix = data.corr()
print(corr_matrix)
Here, we are first loading the “tips” dataset using the seaborn library. The tips dataset contains the tip amount for a total bill amount along with some other data. We are interested in the total bill amount and the tip amount only. So, we are creating another DataFrame “data” that contains two columns – the total bill amount and the tip amount.
Now, we are using the DataFrame.corr() function from the pandas library to calculate the correlation matrix. The output of the above program will be like the following: …








































0 Comments