Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
Correlation Matrix in R Programming
Next article icon

Create a correlation Matrix using Python

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Correlation matrix is a table that shows how different variables are related to each other. Each cell in the table displays a number i.e. correlation coefficient which tells us how strongly two variables are together. It helps in quickly spotting patterns, understand relationships and making better decisions based on data.

A correlation matrix can be created using two libraries:

1. Using NumPy Library

NumPy provides a simple way to create a correlation matrix. We can use the np.corrcoef() function to find the correlation between two or more variables.

Example: A daily sales and temperature record is kept by an ice cream store. To determine the relationship between sales and temperature, we can utilize the NumPy library, where x is sales in dollars and y is the daily temperature.

Python
import numpy as np x = [215, 325, 185, 332, 406, 522, 412,      614, 544, 421, 445, 408], y = [14.2, 16.4, 11.9, 15.2, 18.5, 22.1,       19.4, 25.1, 23.4, 18.1, 22.6, 17.2] matrix = np.corrcoef(x, y) print(matrix) 

Output:

[[1.                     0.95750662]   
[0.95750662 1. ]]

2. Using Pandas library

Pandas is used to create a correlation matrix using its built-in corr() method. It helps in analyzing and interpreting relationships between different variables in a dataset.

Example: Let’s create a simple DataFrame with three variables and calculate correlation matrix.

Python
import pandas as pd data = {     'x': [45, 37, 42, 35, 39],     'y': [38, 31, 26, 28, 33],     'z': [10, 15, 17, 21, 12] } dataframe = pd.DataFrame(data, columns=['x', 'y', 'z']) print("Dataframe is : ") print(dataframe) matrix = dataframe.corr() print("Correlation matrix is : ") print(matrix) 

Output:

corelation1

Using Pandas

Example with Real Dataset (Iris Dataset)

In this example we will consider Iris dataset and find correlation between the features of the dataset.

  • dataset = datasets.load_iris(): Loads Iris dataset from sklearn which contains data on flowers’ features like petal and sepal length/width.
  • dataframe[“target”] = dataset.target: Adds target column which contains the species of the iris flowers to the DataFrame.
Python
from sklearn import datasets   import pandas as pd  dataset = datasets. load_iris()   dataframe = pd.DataFrame(data = dataset.data,columns = dataset.feature_names)  dataframe["target"] = dataset.target   matrix = dataframe.corr() print(matrix) 

Output:

correlation-2

Using IRIS dataset

By using libraries like NumPy and Pandas creating a correlation matrix in Python becomes easy and helps in understanding the hidden relationships between different variables in a dataset.

Related Articles:

  • Correlation: Meaning, Significance, Types and Degree of Correlation
  • Correlation Matrix in R Programming
  • How to Create a Correlation Matrix using Pandas?
  • Exploring Correlation in Python
  • Plotting Correlation Matrix using Python


Next Article
Correlation Matrix in R Programming

R

rohanchopra96
Improve
Article Tags :
  • AI-ML-DS
  • Data Science
  • AI-ML-DS With Python
  • Python-numpy
  • Python-pandas

Similar Reads

  • How to Create a Correlation Matrix using Pandas?
    Correlation is a statistical technique that shows how two variables are related. Pandas dataframe.corr() method is used for creating the correlation matrix. It is used to find the pairwise correlation of all columns in the dataframe. Any na values are automatically excluded. For any non-numeric data
    2 min read
  • Convert covariance matrix to correlation matrix using Python
    In this article, we will be discussing the relationship between Covariance and Correlation and program our own function for calculating covariance and correlation using python.  Covariance: It tells us how two quantities are related to one another say we want to calculate the covariance between x an
    5 min read
  • How to Plot a Correlation Matrix into a Graph Using R
    A correlation matrix is a table showing correlation coefficients between sets of variables. It's a powerful tool for understanding relationships among variables in a dataset. Visualizing a correlation matrix as a graph can provide clearer insights into the data. This article will guide you through t
    4 min read
  • How to Create Correlation Heatmap in R
    In this article let's check out how to plot a Correlation Heatmap in R Programming Language. Analyzing data usually involves a detailed analysis of each feature and how it's correlated with each other. It's essential to find the strength of the relationship between each feature or in other words how
    7 min read
  • Correlation Matrix in R Programming
    Correlation refers to the relationship between two variables, specifically the degree of linear association between them. In R, a correlation matrix represents this relationship as a range of values between -1 and 1. A value of -1 indicates a perfect negative linear relationship.A value of 1 indicat
    5 min read
  • How to Calculate Autocorrelation in Python?
    Correlation generally determines the relationship between two variables. Correlation is calculated between the variable and itself at previous time steps, such a correlation is called Autocorrelation. Method 1 : Using lagplot() The daily minimum temperatures dataset is used for this example. As the
    3 min read
  • Cross-correlation Analysis in Python
    Cross-correlation analysis is a powerful technique in signal processing and time series analysis used to measure the similarity between two series at different time lags. It reveals how one series (reference) is correlated with the other (target) when shifted by a specific amount. This information i
    5 min read
  • How to Find cofactor of a matrix using Numpy
    In this article, we are going to see how to find the cofactor of a given matrix using NumPy. There is no direct way to find the cofactor of a given matrix using Numpy. Deriving the formula to find cofactor using the inverse of matrix in Numpy Formula to find the inverse of a matrix: A-1 = ( 1 / det(
    2 min read
  • How to Calculate Rolling Correlation in Python?
    Correlation generally determines the relationship between two variables. The rolling correlation measure the correlation between two-time series data on a rolling window Rolling correlation can be applied to a specific window width to determine short-term correlations.  Calculating Rolling Correlati
    2 min read
  • How to create a constant matrix in Python with NumPy?
    A matrix represents a collection of numbers arranged in the order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. A constant matrix is a type of matrix whose elements are the same i.e. the element does not change irrespective of any index value th
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences