• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

基于python进行抽样分布描述及实践详解

python 搞代码 4年前 (2022-01-09) 14次浏览 已收录 0个评论

本次选取泰坦尼克号的数据,利用python进行抽样分布描述及实践。

备注:数据集的原始数据是泰坦尼克号的数据,本次截取了其中的一部分数据进行学习。Age:年龄,指登船者的年龄。Fare:价格,指船票价格。Embark:登船的港口。

1、按照港口分类,使用python求出各类港口数据 年龄、车票价格的统计量(均值、方差、标准差、变异系数等)。

import pandas as pd
df = pd.read_excel('/Users/Downloads/data.xlsx',usecols = [1,2,3] )
#拿到港口'Embarked'、年龄'Age'、价格'Fare'的数据
df2 = df.groupby(['Embarked'])
#按照港口'Embarked'分类后,查看 年龄、车票价格的统计量。
# 变异系数 = 标准差/平均值
def cv(data):
  return data.std()/data.var()

df2 = df.groupby(['Embarked']).agg(['count','min','max','median','mean','var','std',cv])
df2 = df2.apply(lambda x:round(x,2))
df2_age = df2['Age']
df2_fare = df2['Fare']

分类后 年龄及价格统计量描述数据如下图:

年龄统计量

价格统计量

2、画出价格的分布图像,验证数据服从何种分布(正态?卡方?还是T?)

2.1 画出船票的直方图:

plt.hist(df['Fare'],20,normed=1, alpha=0.75)
plt.title('Fare')
plt.grid(True)

船票价格的直方图及概率分布

2.2 验证是否符合正态分布?

#分别用kstest、shapiro、normaltest来验证分布系数
ks_test = kstest(df['Fare'], 'norm')
#KstestResult(statistic=0.99013849978633, pvalue=0.0)

shapiro_test = shapiro(df['Fare'])
#shapiroResult(0.5256513357162476, 7.001769945799311e-40)

normaltest_test = normaltest(df['Fare'],axis=0) 
#NormaltestResult(statistic=715.0752414548335, pvalue=5.289130045259168e-156)

以上三种检测结果表明 p<5%,因此 船票数据不符合正态分布。

绘制拟合正态分布曲线:

fare = df['Fare']

plt.figure()
fare.plot(kind = 'kde')   #原始数据的正态分布

M_S = stats.norm.fit(fare)  #正态分布拟合的平均值loc,标准差 scale
normalDistribution = stats.norm(M_S[0], M_S[1])  # 绘制拟合的正态分布图
x = np.linspace(normalDistribution.ppf(0.01), normalDistribution.ppf(0.99), 100)
plt.plot(x, normalDistribution.pdf(x), c='orange')
plt.xlabel('Fare about Titanic')
plt.title('Titanic[Fare] on NormalDistribution', size=20)
plt.legend(['Origin', 'NormDistribution'])

船票拟合正态分布曲线
本文来源gao@daima#com搞(%代@#码@网2

2.3 验证是否符合T分布?

T_S = stats.t.fit(fare)
df = T_S[0] 
loc = T_S[1] 
scale = T_S[2] 
x2 = stats.t.rvs(df=df, loc=loc, scale=scale, size=len(fare))
D, p = stats.ks_2samp(fare, x2) # (0.25842696629213485 2.6844476044528504e-21)

p = 2.6844476044528504e-21 ,p < alpha,拒绝原假设,价格数据不符合t分布。

对票价数据进行T分布拟合:

plt.figure()
fare.plot(kind = 'kde') 
TDistribution = stats.t(T_S[0], T_S[1],T_S[2])  # 绘制拟合的T分布图
x = np.linspace(TDistribution.ppf(0.01), TDistribution.ppf(0.99), 100)
plt.plot(x, TDistribution.pdf(x), c='orange')
plt.xlabel('Fare about Titanic')
plt.title('Titanic[Fare] on TDistribution', size=20)
plt.legend(['Origin', 'TDistribution'])

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:基于python进行抽样分布描述及实践详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址