I have a simple dataframe:
>>> df = pd.DataFrame(np.random.randint(0,5,(20, 2)), columns=['col1','col2'])
>>> df['ind1'] = list('AAAAAABBBBCCCCCCCCCC')
>>> df.set_index(['ind1'], inplace=True)
>>> df
col1 col2
ind1
A 0 4
A 1 2
A 1 0
A 4 1
A 1 3
A 0 0
B 0 4
B 2 0
B 3 1
B 0 3
C 1 3
C 2 1
C 4 0
C 4 0
C 4 1
C 3 0
C 4 4
C 0 2
C 0 2
C 1 2
我正在尝试获取其两列的滚动相关系数:
>>> df.groupby(level=0).rolling(3,min_periods=1).corr()
ind1
A <class 'pandas.core.panel.Panel'>
Dimensions: ...
B <class 'pandas.core.panel.Panel'>
Dimensions: ...
C <class 'pandas.core.panel.Panel'>
Dimensions: ...
dtype: object
问题在于结果是一系列的面板:
>>> type(df.groupby(level=0).rolling(3,min_periods=1).corr())
pandas.core.series.Series
我能够单独为每一行获取所需的系数...
>>> df.groupby(level=0).rolling(3,min_periods=1).corr()['A']
<class 'pandas.core.panel.Panel'>
Dimensions: 10 (items) x 2 (major_axis) x 2 (minor_axis)
Items axis: C to C
Major_axis axis: col1 to col2
Minor_axis axis: col1 to col2
>>> df.groupby(level=0).rolling(3,min_periods=1).corr().loc['A'].ix[2]
col1 col2
col1 1.000000 -0.866025
col2 -0.866025 1.000000
>>> df.groupby(level=0).rolling(3,min_periods=1).corr().loc['A'].ix[2,'col1','col2']
-0.86602540378443849
...但我不知道如何切分结果(一系列的面板),以便将结果作为列分配给现有数据框。类似于:
df['cor_coeff'] = df.groupby(level=0).rolling(3,min_periods=1).corr()['some slicing']
有什么线索吗?或者有更好的方法来获得滚动相关系数吗?