按时间和组别 Z-score

f1r*_*cer 1 python pandas scikit-learn pandas-groupby

我有一个具有以下数据样式的数据框

我正在尝试按每个月为样式列中的每个公司计算 3 个因素(F1、F2、F3)的 z 分数(标准化) 比如说 2014 年 8 月 31 日,我想计算 z 分数(F1、F2 , F3 单独)在该风格(例如建筑材料)内为该月的该风格同行中的每个公司。同样在 2014 年 8 月 31 日,我想计算该月每个拥有“电子设备、仪器和组件”的公司的样式(例如电子设备、仪器和组件)的 z 分数。并且每个月重复这个过程。回顾一下,首先从日期开始,然后计算每种样式中的 z-score,然后每个月重复一次。

我尝试首先定义 z-score zscr=lambda x: (xx.mean())/x.std() 然后按日期、样式分组但没有得到想要的结果。

先感谢您

         Date  Name                                        Style   ID  \
0   8/31/2014   XYZ                          Construction Materials  ABC   
1   9/30/2014   XYZ                          Construction Materials  ABC   
2  10/31/2014   XYZ                          Construction Materials  ABC   
3  11/30/2014   XYZ                          Construction Materials  ABC   
4   8/31/2014  Acme  Electronic Equipment, Instruments & Components  KYZ   
5   9/30/2014  Acme  Electronic Equipment, Instruments & Components  KYZ   
6  10/31/2014  Acme  Electronic Equipment, Instruments & Components  KYZ   

         F1        F2        F3  
0  0.032111  0.063330  0.027733  
1  0.068824  0.158614  0.032489  
2  0.076838  0.034735  0.020062  
3  0.020903  0.154653  0.056860  
4  0.032807  1.099790  0.233216  
5 -0.014995  0.814866  0.498432  
6 -0.002233  1.954578  0.727823  
Run Code Online (Sandbox Code Playgroud)

2014 年 8 月 31 日具有 3 个名称的风格建筑材料的详细示例

Date    Name    Style   F1  F2  F3  Avg F1  Avg F2  Avg F3  Std F1  Std F2  Std F3  Zscore F1   Zscore F2   Zscore F3
8/31/2014   XYZ Construction Materials  ABC 0.0321  0.0633  0.0277  0.0292  0.5066  0.3623  0.0219  0.5091  0.3078  0.131514468 -0.870730766    -1.087062133
8/31/2014   ABC Construction Materials  XKSD    0.0495  0.3939  0.4258  0.0292  0.5066  0.3623  0.0219  0.5091  0.3078  0.927735574 -0.221422977    0.206304231
8/31/2014   HCAG Construction Materials TETR    0.0061  1.0626  0.6334  0.0292  0.5066  0.3623  0.0219  0.5091  0.3078  -1.059250041    1.092153743 0.880757903
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 6

我相信你正在寻找groupby+ transform

names = ['F1', 'F2', 'F3']
zscore = lambda x: (x - x.mean()) / x.std()
df[names] = df.groupby([df.Date, df.Style])[names].transform(zscore)
Run Code Online (Sandbox Code Playgroud)