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
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
How to Calculate Rolling Correlation in R?
Next article icon

How to Calculate Rolling Correlation in Python?

Last Updated : 29 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Correlation in Python

Let's use sales data of two products A and B in the last 60 months to calculate the rolling correlation. Pandas package provides a function called rolling.corr() to calculate the rolling correlation.

Syntax:

data1.rolling(width).corr(data2)

Where, 

  • data1, data2 - data/column of interest (type series)
  • width - Rolling window width (int)

Note: The width of the rolling window should be 3 or greater in order to calculate correlations.

Data Used:  

Python3
# import pandas module import pandas as pd  # read the data data = pd.read_csv('product_sales.csv')  # display top 10 rows print(data.head(10))  # display column names print(data.columns) 

Output:

Example 2:

Here, we used the window width of 6, which shows the successive 6 months rolling correlation. We could see a significant correlation between two products sales any sudden dip or rise in correlation signals an unusual event, that caused the dip.

Python3
data['Product A'].rolling(6).corr(data['Product B'])  # formatting the output k = 1 for i, j in enumerate(data['Product A'].rolling(6).corr(data['Product B'])):     if (i >= 5 and i < 12):         print(f'The correlation in sales during months\         {k} through {i+1} is {j}')         i = 0         k += 1 

Output:

Now's let us try the same for 3-month correlation as shown below,

Example 3:

Python3
data['Product A'].rolling(3).corr(data['Product B'])  # formatting the output k = 1 for i, j in enumerate(data['Product A'].rolling(3).corr(data['Product B'])):     if (i >= 3 and i < 12):         print(             f'The correlation in sales during months {k} \             through {i+1} is {j}')         i = 0         k += 1 

Output:


Next Article
How to Calculate Rolling Correlation in R?

J

jssuriyakumar
Improve
Article Tags :
  • Python
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • How to Calculate Rolling Correlation in R?
    In this article, we will discuss Rolling Correlation in R Programming Language. Correlation is used to get the relationship between two variables. It will result in 1 if the correlation is positive.It will result in -1 if the correlation is negative.it will result in 0 if there is no correlation. Ro
    2 min read
  • How to Calculate Polychoric Correlation in R?
    In this article, we will discuss how to calculate polychoric correlation in R Programming Language. Calculate Polychoric Correlation in R Correlation measures the relationship between two variables. we can say the correlation is positive if the value is 1, the correlation is negative if the value is
    2 min read
  • How to Calculate Partial Correlation in R?
    In this article, we will discuss how to calculate Partial Correlation in the R Programming Language. Partial Correlation helps measure the degree of association between two random variables when there is the effect of other variables that control them. in partial correlation in machine learning It g
    3 min read
  • How to Calculate Point-Biserial Correlation in R?
    In this article, we will discuss how to calculate Point Biserial correlation in R Programming Language. Correlation measures the relationship between two variables. we can say the correlation is positive if the value is 1, the correlation is negative if the value is -1, else 0. Point biserial correl
    2 min read
  • How to Calculate Cross Correlation in R?
    In this article we will discuss how to calculate cross correlation in R programming language. Correlation is used to get the relation between two or more variables. The result is 0, if there is no correlation between two variablesThe result is 1, if there is positive correlation between two variable
    1 min read
  • How to Calculate Partial Correlation in Excel?
    Partial correlation helps find the correlation between the two variables by removing the effect of the third variable. There can be situations when the relations between variables can be many. This could reduce the accuracy of correlation or could also give wrong results. Partial correlation removes
    5 min read
  • How to Calculate Cosine Similarity in Python?
    In this article, we calculate the Cosine Similarity between the two non-zero vectors. A vector is a single dimesingle-dimensional signal NumPy array. Cosine similarity is a measure of similarity, often used to measure document similarity in text analysis. We use the below formula to compute the cosi
    3 min read
  • How to Calculate Correlation By Group in R
    Calculating correlation by group in R Programming Language involves finding the correlation coefficient between two variables within each subgroup defined by another variable. In R, correlation by group can be achieved by using the cor() function along with other functions like group_by() from the '
    5 min read
  • How to Calculate Spearman Rank Correlation in Excel?
    We have noticed a general trend that with an increase in the height of a person, its weight also increases. This happens because there is a positive correlation between height and weight. As one variable increases, the other one also increases, but with this, we only get the quality measure of the d
    8 min read
  • How to Calculate Point-Biserial Correlation in Excel?
    The Point-Biserial Correlation Coefficient is a correlation metric that measures the degree of relationship between a continuous and a binary variable. The connection between a binary variable, x, and a continuous variable, y, is measured using point-biserial correlation. Binary variables are widely
    3 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