python - 如何找到 2 个变量之间但跨越不同时间线的相关性(“滞后相关性”)
问题描述
假设我正在销售相互互补的商品。我试图找出商品销售之间的相关性,但在不同的销售日期。
(因为我认为item01
d-day 的销售可能会影响item02~99
on的销售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 行,并将 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')
这将要求您将数据集减少您选择移动的时间段数,因此根据您的样本量,您可能需要注意不要选择太长的时间段。
推荐阅读
- javascript - 在基于时间的动画中取消运动的逻辑
- excel - VBA 错误处理程序未在错误处理程序中检测到错误
- python - 使用 if else 条件更新 pandas 数据框值?
- c# - 减去时间跨度并将小时和分钟返回到十进制
- typescript - 响应函数将端口替换为未定义
- vue.js - 如何将 Vue Bootstrap Modal 附加到不同的父级?
- asp.net-mvc - 在 MVC 视图中使用资源文件变量
- f# - Deedle、F# 和 Frame.map 的问题
- python - PermissionError:[Errno 13] 权限被拒绝 aws ec2
- scala - 登录火花结构化流/SparkException:任务不可序列化