【问题标题】:How to calculate the ewm correlation coefs after groupbygroupby后如何计算ewm相关系数
【发布时间】:2017-09-23 13:11:38
【问题描述】:

E.G,我有以下 csv 数据(实际上有不止一组 g):

G,T,x,y
g,1,3,4
g,2,4,5
g,3,6,1
g,4,7,2
g,5,8,3
g,6,9,8

我想计算每组的 x 和 y 之间的指数加权相关系数。所以我期待结果:

G T     namedWhatever
g 1         NaN
g 2    1.000000
g 3   -0.867510
g 4   -0.792758
g 5   -0.510885
g 6    0.413379

实际上可以通过以下方式计算:

dat.loc['g'].ewm(halflife=3).corr().loc[:, 'x', 'y']
Out[5]: 
T
1         NaN
2    1.000000
3   -0.867510
4   -0.792758
5   -0.510885
6    0.413379
Name: y, dtype: float64

我没有运气的尝试:

In [3]: dat = pd.read_csv('test.csv').set_index(['G', 'T'])

In [4]: dat.groupby(level='G').transform(lambda x: x.ewm(halflife=3).corr())
Out[4]: 
       x    y
G T          
g 1  NaN  NaN
  2  1.0  1.0
  3  1.0  1.0
  4  1.0  1.0
  5  1.0  1.0
  6  1.0  1.0

正确的做法是什么?我的熊猫版本是 0.19.2 和 python 3.6。

【问题讨论】:

标签: python pandas


【解决方案1】:

问题是corr 返回相关矩阵。因此,当您执行 ewm.corr 时,它会返回一个面板。 所以需要提取额外的对角线分量来得到相关系数。

带有循环的显式解决方案是:

res = pd.concat([el.ewm(halflife = 3).corr().xs('x', axis = 1).loc['y', :] for key, el in dat.groupby(level = 'G')])

如果你检查el.ewm(halflife = 3).corr(),这会更清楚:

el.ewm(halflife = 3).corr()
Out[54]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 6 (items) x 2 (major_axis) x 2 (minor_axis)
Items axis: (g, 1) to (g, 6)
Major_axis axis: x to y
Minor_axis axis: x to y

this answer 之后,我意识到您可以通过使用上面的表达式但在分组对象的apply 而不是transform 方法中避免循环。

dat.groupby(level='G').apply(lambda x: x.ewm(halflife=3).corr().xs('x', axis = 1).loc['y', :]).T

在这两种情况下,我都获得了预期的输出:

res
Out[55]: 
G  T
g  1         NaN
   2    1.000000
   3   -0.867510
   4   -0.792758
   5   -0.510885
   6    0.413379
Name: y, dtype: float64

【讨论】:

  • 您的解决方案是对的,但是,我想避免使用 for 循环。
  • 添加无循环解决方案
  • 很高兴它有帮助! :)
猜你喜欢
  • 2018-09-10
  • 1970-01-01
  • 2012-06-25
  • 2011-12-20
  • 1970-01-01
  • 2021-09-17
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多