【问题标题】:How to find correlation between 2 variables but cross different timeline ('lagged correlation')如何找到 2 个变量之间但跨越不同时间线的相关性(“滞后相关性”)
【发布时间】:2019-09-30 22:32:53
【问题描述】:

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

(因为我认为 item01 在 d 日的销售额可能会影响 item02~99d+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    ...

...    ...     ...     ...    ...    ...

我学会了如何使用 pandas 数据框的.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  ...

...           ...    ...

【问题讨论】:

  • 这称为滞后相关
  • 例如相关性滞后 n 天
  • 显然,您正在寻找时间序列的自相关pandas.pydata.org/pandas-docs/stable/reference/api/…
  • @rafaelc:然后是 滞后自相关,例如“找到具有峰值自相关的滞后”
  • @smci 滞后自相关 是多余的。自相关意味着已经存在滞后

标签: python pandas correlation lag


【解决方案1】:

创建按 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)

接下来,将 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')

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

【讨论】:

  • 非常感谢!有用!感谢您的回答。我刚刚更改了 'pd.concat(frames, axis=1)'
猜你喜欢
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2023-01-30
  • 2021-11-06
  • 2019-10-30
  • 1970-01-01
相关资源
最近更新 更多