Pandas分组和计算Z-Score

12

我有一个数据框,长这个样子:

pd.DataFrame([[1, 10, 14], [1, 12, 14], [1, 20, 12], [1, 25, 12], [2, 18, 12], [2, 30, 14], [2, 4, 12], [2, 10, 14]], columns = ['A', 'B', 'C'])

    A   B   C
0   1   10  14
1   1   12  14
2   1   20  12
3   1   25  12
4   2   18  12
5   2   30  14
6   2   4   12
7   2   10  14

我的目标是获取相对于列A和C的组的z分数。我知道可以计算每个组的平均值和标准偏差。

test.groupby(['A', 'C']).mean()    
        B
A   C   
1   12  22.5
    14  11.0
2   12  11.0
    14  20.0

test.groupby(['A', 'C']).std()
        B
A   C   
1   12  3.535534
    14  1.414214
2   12  9.899495
    14  14.142136

现在,针对B列中的每个项目,我想基于这些均值和标准偏差计算它们的Z分数。因此,第一个结果将是(10 - 11) / 1.41。我觉得应该有一种不太复杂的方法可以做到这一点,但我卡在了如何继续上。如果有人能指点我正确的方向或者需要我澄清什么东西,请告诉我!

1个回答

16

使用transform来操作

Mean=test.groupby(['A', 'C']).B.transform('mean')    
Std=test.groupby(['A', 'C']).B.transform('std')

那么

(test.B - Mean) / Std

来自 scipy 的一个名为 zscore 的函数。

from scipy.stats import zscore
test.groupby(['A', 'C']).B.transform(lambda x : zscore(x,ddof=1))
Out[140]: 
0   -0.707107
1    0.707107
2   -0.707107
3    0.707107
4    0.707107
5    0.707107
6   -0.707107
7   -0.707107
Name: B, dtype: float64

好的,展示我的号码吧 呵呵

(test.B - Mean) / Std ==test.groupby(['A', 'C']).B.transform(lambda x : zscore(x,ddof=1))
Out[148]: 
0    True
1    True
2    True
3    True
4    True
5    True
6    True
7    True
Name: B, dtype: bool

请展示您的数字核对结果。重复出现的数字看起来有些可疑。 - Golden Lion
@GoldenLion 祝你好运 - BENY
@GoldenLion 我正在使用提供的数据... 你尝试过了吗?只是试一下。 - BENY
df=pd.DataFrame([[1, 10, 14], [1, 12, 14], [1, 20, 12], [1, 25, 12], [2, 18, 12], [2, 30, 14], [2, 4, 12], [2, 10, 14]], columns = ['A', 'B', 'C']) print(df.groupby(['A','B']).transform(zscore)) 我的代码生成了C值的NaN z分数 - Golden Lion
1
@GoldenLion,BENY上面的方法是正确的。之所以z分数都相同为0.707107(无论是正数还是负数),是因为原始用户发布的样本df每个groupby只包含两个“结果”。换句话说,每个'A'和'C'的groupby只有两行结果。当对这些行求平均值,然后计算z分数时,它将得到相同的0.707107(一个为正数,另一个为负数)。要查看BENY的代码是否正确,只需向原始df添加另一行,例如[1, 15, 14],您将看到z分数发生变化。 - BGG16
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接