如何在Python中计算滚动相关度

如何在Python中计算滚动相关度

相关性通常决定了两个变量之间的关系。滚动相关测量两个时间序列数据在滚动窗口上的相关性 滚动相关可以应用于特定的窗口宽度,以确定短期相关性。

在Python中计算滚动相关度

让我们使用两个产品A和B在过去60个月中的销售数据来计算滚动相关关系。Pandas包提供了一个名为rolling.corr()的函数来计算滚动相关性。

语法:

data1.rolling(width).corr(data2)

其中,

  • data1, data2 – 感兴趣的数据/列(类型系列)
  • width – 滚动窗口的宽度(int)

注意:滚动窗口的宽度应该是3或更大,以便计算相关关系

使用的数据:

# 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)

输出:

如何在Python中计算滚动相关度?

示例 2:

在这里,我们使用了6的窗口宽度,它显示了连续6个月的滚动相关关系。我们可以看到两个产品的销售之间有显著的相关性,任何相关性的突然下降或上升都预示着一个不寻常的事件,导致了这个下降。

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

输出:

如何在Python中计算滚动相关度?

现在让我们对3个月的相关性进行同样的尝试,如下所示。

示例 3:

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

输出 :

如何在Python中计算滚动相关度?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程