首页 > 解决方案 > 如何找到 2 个变量之间但跨越不同时间线的相关性(“滞后相关性”)

问题描述

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

(因为我认为item01d-day 的销售可能会影响item02~99on的销售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  ...

...           ...    ...

标签: pythonpandascorrelationlag

解决方案


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

df_shifted = df_sales.shift(periods=30)
df_shifted.columns = ['Item01_30','Item02_30','Item03_30','Item04_30']

会将所有记录向上移动 30 行,并将 NaN 值留在观察值 0-29 中。然后在原始数据框的末尾添加 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)

接下来,将 df_shifted 和 df_sales 合并到一个数据帧中:

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

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


推荐阅读