使用Python实现抽样分布的正态分布、卡方分布、T分布

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
path = ‘C:/Users/统计学学习/data.xlsx’
data = pd.read_excel(path)

embark = data.groupby([‘Embarked’])

embark_basic = data.groupby([‘Embarked’]).agg([‘count’,‘min’,‘max’,‘median’,‘mean’,‘var’,‘std’])

age_basic = embark_basic[‘Age’]
fare_basic = embark_basic[‘Fare’]

age_basic
fare_basic

import seaborn as sns
sns.set_palette(“hls”) #设置所有图的颜色,使用hls色彩空间
sns.distplot(data[‘Age’],color=“r”,bins=10,kde=True)
plt.title(‘Age’)
plt.xlim(-10,80)
plt.grid(True)
plt.show()

from scipy import stats
from scipy import stats
age = data[‘Age’]

plt.figure()
age.plot(kind = ‘kde’) #原始数据的正态分布

M_S = stats.norm.fit(age) #正态分布拟合的平均值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(‘Age about Titanic’)
plt.title(‘Age on NormalDistribution’, size=20)
plt.legend([‘age’, ‘NormDistribution’])

验证是否服从T分布

np.random.seed(1)
ks = stats.t.fit(age)
df = ks[0]
loc = ks[1]
scale = ks[2]
ks2 = stats.t.rvs(df=df, loc=loc, scale=scale, size=len(age))
stats.ks_2samp(age, ks2)
Ks_2sampResult(statistic=0.08286516853932585, pvalue=0.014103597072570409)
###由检验结果知,p <0.05,所以拒绝原假设,认为数据不服从T分布
plt.figure()
age.plot(kind = ‘kde’)
TDistribution = stats.t(ks[0], ks[1],ks[2])
x = np.linspace(TDistribution.ppf(0.01), TDistribution.ppf(0.99), 100)
plt.plot(x, TDistribution.pdf(x), c=‘orange’)
plt.xlabel(‘age about Titanic’)
plt.title(‘age on TDistribution’, size=20)
plt.legend([‘age’, ‘TDistribution’])

验证数据是否服从卡方分布

chi_S = stats.chi2.fit(age)
df_chi = chi_S[0]
loc_chi = chi_S[1]
scale_chi = chi_S[2]
chi2 = stats.chi2.rvs(df=df_chi, loc=loc_chi, scale=scale_chi, size=len(age))
stats.ks_2samp(age, chi2)
Ks_2sampResult(statistic=0.058988764044943826, pvalue=0.16233843312998728)
###由检验结果知,p <0.05,所以拒绝原假设,认为数据不服从卡方分布
对数据进行卡方拟合
plt.figure()
age.plot(kind = ‘kde’)
chiDistribution = stats.chi2(chi_S[0], chi_S[1],chi_S[2]) # 绘制拟合的正态分布图
x = np.linspace(chiDistribution.ppf(0.01), chiDistribution.ppf(0.99), 100)
plt.plot(x, chiDistribution.pdf(x), c=‘orange’)
plt.xlabel(‘age about Titanic’)
plt.title(‘age on chi-square_Distribution’, size=20)
plt.legend([‘age’, ‘chi-square_Distribution’])

你可能感兴趣的:(统计学学习)