如何找到两个变量之间的相关性,但交叉不同的时间轴('滞后相关性')

2024-03-28 20:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我卖的东西是相互补充的。 我想找出商品销售之间的相关性,但销售日期不同。你知道吗

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

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  ...

...           ...    ...

Tags: dataframedfsalescorrday1day4day2day3
1条回答
网友
1楼 · 发布于 2024-03-28 20:35:17

创建按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\u shifted和df\u 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')

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

相关问题 更多 >