【问题标题】:Aligning Excel correlation window with Pandas correlation window将 Excel 相关窗口与 Pandas 相关窗口对齐
【发布时间】:2019-05-04 18:32:47
【问题描述】:

我在 EXCEL 中使用 Var_1 和 Var_2 的 3 个周期窗口创建了滚动相关性。Excel 代码是:

=CORREL(B2:B4,C2:C4)

我正在尝试在 Python 中创建相同的结果。但是,当我执行代码时,我的结果在 Python 中向下移动了 1 行。我还得到一个 1.0 作为第一行值,我不明白。 该工作表从 Excel 读入 Python 并保存为 pandas 数据框。 这是图片。 我创建的 Python 代码是为了重新创建这种滚动相关性。

df2 = pd.DataFrame((df.iloc[::1,1]).rolling(window = 3,min_periods = 1,center = True).corr((df.iloc[::1,2])))

【问题讨论】:

    标签: python excel pandas time-series rolling-computation


    【解决方案1】:

    您可能可以将统计模块与列表理解一起使用:

    df['r_value'] = [scipy.stats.linregress(df['Var_1'].loc[i:i+2], df['Var_2'].loc[i:i+2])[2] for i in range(len(df))]
    
        Var_1   Var_2   r_value
    0   5        -55    -0.525909
    1   41       -44    -0.455413
    2   85       -65    0.032059
    3   55       -77    0.896258
    4   65       -25    0.388874
    5   47       -77    0.474843
    6   25       -48    1.000000
    7   63       -12    0.000000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2015-01-29
      • 2012-11-27
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多