在每列上计算Pandas DataFrame的自相关性

16

我想计算Pandas DataFrame中列之间滞后一阶的自相关系数。我的数据片段如下:

            RF        PC         C         D        PN        DN         P
year                                                                      
1890       NaN       NaN       NaN       NaN       NaN       NaN       NaN
1891 -0.028470 -0.052632  0.042254  0.081818 -0.045541  0.047619 -0.016974
1892 -0.249084  0.000000  0.027027  0.067227  0.099404  0.045455  0.122337
1893  0.653659  0.000000  0.000000  0.039370 -0.135624  0.043478 -0.142062

在整个年份期间,我希望计算每一列(RFPC等)的滞后一阶自相关系数。

为了计算自相关系数,我提取了每一列的两个时间序列,它们的起始和结束数据相差一年,然后用numpy.corrcoef计算相关系数。

例如,我写下了以下代码:

numpy.corrcoef(data[['C']][1:-1],data[['C']][2:])

(整个DataFrame称为data
但是,该命令不幸地返回:

array([[ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       ..., 
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan]])

有人能友善地向我介绍如何计算自相关性吗?

4个回答

23

18

.autocorr 适用于Series,而不是DataFrames。您可以使用.apply来应用于DataFrame:

def df_autocorr(df, lag=1, axis=0):
    """Compute full-sample column-wise autocorrelation for a DataFrame."""
    return df.apply(lambda col: col.autocorr(lag), axis=axis)
d1 = DataFrame(np.random.randn(100, 6))

df_autocorr(d1)
Out[32]: 
0    0.141
1   -0.028
2   -0.031
3    0.114
4   -0.121
5    0.060
dtype: float64

您可以使用指定窗口计算滚动自相关性,如下所示(这就是 .autocorr 在后台执行的操作):
def df_rolling_autocorr(df, window, lag=1):
    """Compute rolling column-wise autocorrelation for a DataFrame."""

    return (df.rolling(window=window)
        .corr(df.shift(lag))) # could .dropna() here

df_rolling_autocorr(d1, window=21).dropna().head()
Out[38]: 
        0      1      2      3      4      5
21 -0.173 -0.367  0.142 -0.044 -0.080  0.012
22  0.015 -0.341  0.250 -0.036  0.023 -0.012
23  0.038 -0.329  0.279 -0.026  0.075 -0.121
24 -0.025 -0.361  0.319  0.117  0.031 -0.120
25  0.119 -0.320  0.181 -0.011  0.038 -0.111

5

您应该使用:

numpy.corrcoef(df['C'][1:-1], df['C'][2:])

df[['C']] 表示只有一列的数据框,而 df['C'] 是一个包含 C 列值的序列。


2

因为我相信我们需要一个与最高相关性相对应的窗口的使用情况更为普遍,所以我添加了另一个函数,该函数返回每个特征的窗口长度。

# Find autocorrelation example.
def df_autocorr(df, lag=1, axis=0):
    """Compute full-sample column-wise autocorrelation for a DataFrame."""
    return df.apply(lambda col: col.autocorr(lag), axis=axis)

def df_rolling_autocorr(df, window, lag=1):
    """Compute rolling column-wise autocorrelation for a DataFrame."""

    return (df.rolling(window=window)
        .corr(df.shift(lag))) # could .dropna() here

def df_autocorr_highest(df, window_min, window_max, lag_f):
    """Returns a dictionary containing highest correlation coefficient wrt window length."""
    df_corrs = pd.DataFrame()
    df_corr_dict = {}
    for i in range(len(df.columns)):
        corr_init = 0
        corr_index = 0
        for j in range(window_min, window_max): 
            corr = df_rolling_autocorr(df.iloc[:,i], window=j, lag=lag_f).dropna().mean()
            if corr > corr_init:
                corr_init = corr
                corr_index = j
        corr_label = df.columns[i] + "_corr"    
        df_corr_dict[corr_label] = [corr_init, corr_index]
    return df_corr_dict

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接