从均值和标准差计算 Z 分数

Z-score calculation from mean and st dev

我想问一下,如果我已经知道临界值、均值和标准偏差,是否有任何流行的软件包如:numpy、scipy 等具有计算 Z 分数的内置函数。

我通常这样做:

def Zscore(xcritical, mean, stdev):
    return (xcritical - mean)/stdev

#example:
xcritical = 73.06
mean = 72
stdev = 0.5

zscore = Zscore(xcritical, mean, stdev)

之后我使用 scipy.stats.norm.cdf 来计算 x 低于 xcritical 的概率。

import scipy.stats as st
print(st.norm.cdf(zscore))

我想知道我是否可以以某种方式简化它。我知道有 scipy.stats.zscore 函数,但它需要一个样本数组而不是样本统计信息。

在你的问题中,我不确定你计算'x'低于'xcritical'的概率是什么意思,因为你没有定义'x'。无论如何,我将回答如何计算 'x' 值的 z-score。

根据 scipy.stats.norm 文档 here,似乎没有内置方法来计算 z-score值('xcritical' 在你的情况下),给定平均值和标准偏差。但是,您可以使用内置方法 cdfppf 进行相同的计算。考虑以下代码段(值与您在 post 中使用的值相同,其中 'xcritical' 是您希望计算 z-score 的值):

xcritical = 73.06
mean = 72
stdev = 0.5

p = norm.cdf(x=xcritical,loc=mean,scale=stdev)
z_score = norm.ppf(p)
print('The z-score for {} corresonding to {} mean and {} std deviation is: {:.3f}'.format(xcritical,mean,stdev,z_score))

这里,我们首先使用norm.cdf( )norm.cdf() 计算正态分布曲线下从负无穷大到 'x' 值(在本例中为 'xritical')的面积百分比。然后,我们将这个概率传给norm.ppf(),得到那个'x'值对应的z-score。 norm.ppf() 是百分比点函数,它产生对应于标准正态分布曲线中通过的下尾概率的 (z) 值。此代码的输出 2.12 与您将从函数 Zscore().

中获得的输出相同

希望对您有所帮助!

一行即可完成;像这样:

>>> import scipy.stats as st
>>> st.norm(mean, stdev).cdf(xcritical))

开始 Python 3.9,标准库提供 zscore function on the NormalDist object as part of the statistics 模块:

NormalDist(mu=72, sigma=.5).zscore(73.06)
# 2.1200000000000045

The life in hours of a battery is known to be approximately normally distributed with standard deviation σ = 1.25 hours. A random sample of 10 batteries has a mean life of x = 40.5 hours. a. Is there evidence to support the claim that battery life exceeds 40 hours? Use α = 0.5.

norm.sf,因为我想知道钟形曲线的右侧是否超过alpha才能回答。

norm.sf(40.5, loc=40, scale=1.25/np.sqrt(10)) #recall the z score formula

p-value = 0.102

Ho: u=40 ; Ha: u>40

因此 p 值大于 alpha,因此我们无法拒绝原假设并得出结论,确实有证据支持电池寿命超过 40 小时。 P 值 0.10 > 0.05 alpha