我有一个简单的数据框:
>>> 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']
有什么线索吗?还是获得滚动相关系数的更好方法?
最佳答案
你的问题是.corr()
在未指定 other
参数的情况下被调用。即使您的数据框只有两列,Pandas 也不知道您真正想要的相关性,因此它会计算所有可能的相关性(col1
x col1
, col1
x col2
, col2
x col1
, col2
x col2
) 和以 2x2 数据结构向您提供结果。如果要从一个相关性中获取结果,则需要通过设置基列和 other
列来指定所需的相关性。如果您不使用 groupby
,您只需这样做:
df['col1'].rolling(min_periods=1, window=3).corr(other=g['col2'])
由于您使用的是 groupby
,因此您需要将其嵌套在带有 lambda 函数的 apply
子句中(或者如果您愿意,可以将其移至单独的函数中):
df.groupby(level=0).apply(lambda g: g['col1'].rolling(min_periods=1, window=3).corr(other=g['col2']))
关于python - 切片系列面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40082844/