【问题标题】:slicing series of panels切片系列面板
【发布时间】:2016-10-17 09:30:24
【问题描述】:

我有一个简单的数据框:

>>> 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']

有什么线索吗?还是获得滚动相关系数的更好方法?

【问题讨论】:

  • 这是一个写得很好的问题——它包含了复制问题所需的一切,它显示了你到目前为止所做的尝试,它显示了你对解决方案的看法喜欢。不错!

标签: python pandas slice


【解决方案1】:

您的问题是 .corr() 在没有指定 other 参数的情况下被调用。即使您的数据框只有两列,Pandas 也不知道您真正想要哪种相关性,因此它会计算所有可能的相关性(col1 x col1col1 x col2col2 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']))

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2014-06-18
    • 2014-05-28
    • 2013-04-30
    • 2020-09-02
    相关资源
    最近更新 更多