如何在pandas中正确找到偏度和峰度?

7
我想知道如何在 Pandas 中正确计算偏度和峰度。Pandas 为 `skew()` 和 `kurtosis()` 函数提供了一些值,但是与 `scipy.stats` 的值相比似乎有很大的差异。应该相信哪一个,是 Pandas 还是 `scipy.stats`?这是我的代码:
import numpy as np
import scipy.stats as stats
import pandas as pd

np.random.seed(100)
x = np.random.normal(size=(20))

kurtosis_scipy = stats.kurtosis(x)
kurtosis_pandas = pd.DataFrame(x).kurtosis()[0]

print(kurtosis_scipy, kurtosis_pandas)
# -0.5270409758168872
# -0.31467107631025604

skew_scipy = stats.skew(x)
skew_pandas = pd.DataFrame(x).skew()[0]

print(skew_scipy, skew_pandas)
# -0.41070929017558555
# -0.44478877631598901

版本:

print(np.__version__, pd.__version__, scipy.__version__)
1.11.0 0.20.0 0.19.0

相关链接:https://dev59.com/8FgR5IYBdhLWcg3wAJFK - piRSquared
还有相关内容:https://dev59.com/Savka4cB1Zd3GeqPqkeE#50277666 - ALollz
2个回答

8

bias=False

print(
    stats.kurtosis(x, bias=False), pd.DataFrame(x).kurtosis()[0],
    stats.skew(x, bias=False), pd.DataFrame(x).skew()[0],
    sep='\n'
)

-0.31467107631025515
-0.31467107631025604
-0.4447887763159889
-0.444788776315989

4
Pandas计算总体峰度的无偏估计量。 请查看维基百科上的公式:https://www.wikiwand.com/en/Kurtosis

enter image description here

从头计算峰度

import numpy as np
import pandas as pd
import scipy

x = np.array([0, 3, 4, 1, 2, 3, 0, 2, 1, 3, 2, 0,
              2, 2, 3, 2, 5, 2, 3, 999])
xbar = np.mean(x)
n = x.size
k2 = x.var(ddof=1) # default numpy is biased, ddof = 0
sum_term = ((x-xbar)**4).sum()
factor = (n+1) * n / (n-1) / (n-2) / (n-3)
second = - 3 * (n-1) * (n-1) / (n-2) / (n-3)

first = factor * sum_term / k2 / k2

G2 = first + second
G2 # 19.998428728659768

使用numpy/scipy计算峰度

scipy.stats.kurtosis(x,bias=False) # 19.998428728659757

使用pandas计算峰度
pd.DataFrame(x).kurtosis() # 19.998429

同样,您也可以计算偏度。


“从头开始”版本中,“xbar”和“n”变量是什么? - BrunoF
1
@BrunoFacca xbar 是样本均值,n 是样本大小。我已经更新了代码。 - BhishanPoudel

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