Python 如何找到两个变量之间的相关性,但要跨越不同的时间轴(';滞后相关性';)

Python 如何找到两个变量之间的相关性,但要跨越不同的时间轴(';滞后相关性';),python,pandas,correlation,lag,Python,Pandas,Correlation,Lag,假设我卖的东西是相互补充的。 我试图找出商品销售之间的相关性,但是在不同的销售日期 (因为我认为在d日销售item01可能会影响item02~99在d+30的销售) dataframe如下所示 . Item01 Item02 Item03 Item04 ... day1 120 130 140 200 ... day2 200 200 150 119 ... day3 162 110 180

假设我卖的东西是相互补充的。 我试图找出商品销售之间的相关性,但是在不同的销售日期

(因为我认为在d日销售
item01
可能会影响
item02~99
d+30
的销售)

dataframe
如下所示

.    Item01  Item02  Item03 Item04  ... 

day1   120     130     140    200    ...

day2   200     200     150    119    ...

day3   162     110     180    220    ...

day4   170     130     160    190    ...

...    ...     ...     ...    ...    ...
我学会了如何使用熊猫数据框的
.corr()
但我想找出交叉时间相关性

我应该做我自己的回归函数吗

多谢各位

df_sales = pd.DataFrame(dic_sales)

corr = df_sales.corr(method = 'pearson')
corr val

.            item01 Item02 ...

item01(d+30)  0.75   0.46  ...

item02(d+30)  0.44   0.84  ...

...           ...    ...

创建按30天滞后期进行时移的新列,然后对这些列运行corr方法

df_shifted = df_sales.shift(periods=30)
df_shifted.columns = ['Item01_30','Item02_30','Item03_30','Item04_30']
将所有记录向上移动30行,并在观测值0-29中保留NaN值。然后将30个NaN值添加到原始数据帧的末尾:

empty_row = pd.Series([Nan,Nan,Nan,Nan], index=['Item01','Item02','Item03','Item04'])
for i in range(30):
    df_sales = df_sales.append(empty_row)
frames = [df_sales, df_shifted]
df_sales_with_shift = pd.concat(frames, axis=1)
接下来,将df_移位和df_销售合并到一个数据帧中:

empty_row = pd.Series([Nan,Nan,Nan,Nan], index=['Item01','Item02','Item03','Item04'])
for i in range(30):
    df_sales = df_sales.append(empty_row)
frames = [df_sales, df_shifted]
df_sales_with_shift = pd.concat(frames, axis=1)
仅对没有NaN值的行运行corr方法:

df_sales_with_shift[30:len(df_sales_with_shift.index)-30].corr(method ='pearson')

这将要求您将数据集减少您选择的时间段数,因此,根据样本大小,您可能需要注意不要选择太长的时间段。

创建新的列,这些列的时间段被延迟30天,然后对这些列运行corr方法

df_shifted = df_sales.shift(periods=30)
df_shifted.columns = ['Item01_30','Item02_30','Item03_30','Item04_30']
将所有记录向上移动30行,并在观测值0-29中保留NaN值。然后将30个NaN值添加到原始数据帧的末尾:

empty_row = pd.Series([Nan,Nan,Nan,Nan], index=['Item01','Item02','Item03','Item04'])
for i in range(30):
    df_sales = df_sales.append(empty_row)
frames = [df_sales, df_shifted]
df_sales_with_shift = pd.concat(frames, axis=1)
接下来,将df_移位和df_销售合并到一个数据帧中:

empty_row = pd.Series([Nan,Nan,Nan,Nan], index=['Item01','Item02','Item03','Item04'])
for i in range(30):
    df_sales = df_sales.append(empty_row)
frames = [df_sales, df_shifted]
df_sales_with_shift = pd.concat(frames, axis=1)
仅对没有NaN值的行运行corr方法:

df_sales_with_shift[30:len(df_sales_with_shift.index)-30].corr(method ='pearson')

这将要求您将数据集减少您选择移动的时间段数,因此根据您的样本大小,您可能需要注意不要选择太长的时间段。

这称为滞后相关性。g。相关性滞后n天显然,您正在查找时间序列的自相关@rafaelc:然后是滞后自相关,例如“查找峰值自相关的滞后”@smci滞后自相关是多余的。自相关意味着一个滞后,这被称为滞后相关。相关性滞后n天显然,您正在查找时间序列的自相关@rafaelc:然后是滞后自相关,例如“查找峰值自相关的滞后”@smci滞后自相关是多余的。自相关意味着一个滞后,我非常感谢你!它起作用了!谢谢你的回答。我刚刚更改了“pd.concat(frames,axis=1)”,非常感谢!它起作用了!谢谢你的回答。我刚刚更改了“pd.concat(帧,轴=1)”