我的数据框中总共有4列。我想在每一行和第一个滞后行之间生成协方差。我该怎么做?我的数据框的一个子集以及所需的列'协方差'如下:
A1 A2 A3 A4 Covariance
24.54 63.32 47.12 60.66 nan
16.33 64.39 49.72 56.94 73.43
46.38 55.94 42.35 73.43 50.27
基本上,Covariance列应该包含值,就像在Microsoft EXCEL中的行和滞后之间使用COVARIANCE.P公式一样。截至目前,我正在使用滞后变量生成新列,并尝试沿数据帧的一行获取协方差。这是我的代码:
df = pd.DataFrame({'A1':[19, 20, 21],
'A2':[24.54, 16.33, 46.38],
'A3':[63.32, 64.39, 55.94],
'A4':[47.12, 49.72, 42.35]})
df['Lag_A1'] = df['A1].shift(-1)
df['Lag_A2'] = df['A2].shift(-1)
df['Lag_A3'] = df['A3].shift(-1)
df['Lag_A4'] = df['A4].shift(-1)
Main = ['A1', 'A2', 'A3', 'A4']
Lag_1 = ['Lag_1_A1', 'Lag_1_A2', 'Lag_1_A3', 'Lag_1_A4']
Lag_1_Cov = df.apply(lambda x: x[Main].T.cov(x[Lag_1].T))
但是,此代码不起作用。请帮忙。
答案 0 :(得分:1)
如果我理解的话。
df['Cov']=[df.iloc[:,:4].iloc[x].cov(df.iloc[:,:4].shift(1).iloc[x]) for x in range(len(df))]
df
Out[147]:
A1 A2 A3 A4 Covariance Cov
0 24.54 63.32 47.12 60.66 NaN NaN
1 16.33 64.39 49.72 56.94 73.43 369.981333
2 46.38 55.94 42.35 73.43 50.27 143.071233
答案 1 :(得分:0)
您可以使用numpy
进行此计算。但是,我无法复制您的协方差值。
请注意,我们为人口协方差设置了ddof = 0
。
import numpy as np
arr = df.values
df['Covariance'] = [np.nan] + [np.cov(i, j, ddof=0)[0][1] for i, j in zip(arr, arr[1:])]
结果:
A1 A2 A3 A4 Covariance
0 24.54 63.32 47.12 60.66 NaN
1 16.33 64.39 49.72 56.94 277.486000
2 46.38 55.94 42.35 73.43 107.303425