重温统计学--python实现概括性度量
程序员文章站
2022-03-05 14:31:48
...
#导入所需的包
import pandas as pd
import numpy as np
import seaborn as sns
from scipy import stats
#读取数据,并用describe查看数据的分布情况
data = pd.read_excel('./Desktop/实践一.xlsx')
data.describe()
out:
data
count 699.000000
mean 4.417740
std 2.815741
min 1.000000
25% 2.000000
50% 4.000000
75% 6.000000
max 10.000000
#为了方便计算,将数据集转为列表
data1 = list(data['data'])
#通过numpy、stats求得各个指标
print('平均数:',np.mean(data1))
print('下四分位数:',np.quantile(data1,0.25))
print('中位数:',np.median(data1))
print('上四分位数:',np.quantile(data1,0.75))
print('众数:',stats.mode(data1)[0][0])
print('标准差:',np.std(data1))
print('偏态系数:',stats.skew(data1))
print('峰态系数:',stats.kurtosis(data1))
out:
平均数: 4.417739628040057
下四分位数: 2.0
中位数: 4.0
上四分位数: 6.0
众数: 1
标准差: 2.8137258170785375
偏态系数: 0.5915855449527385
峰态系数: -0.6278342838815454
#自定义一个函数,实现以上功能:
def get_data_describe(data):
n = len(data)
m = int(n/2)
m1 = int((n/2))-1
m2 = int((n/2))+1
data = sorted(data)
data_mean = np.sum(data)/n
if n%2 ==0:
data_median = (data[m1]+data[m2])/2
else:
data_median = data[m]
data_range = [data[i]-data_mean for i in range(len(data))]
data_sd = np.sum([pow(x,2) for x in data_range])/n
data_std = np.sqrt(data_sd)
data_sk = np.sum([pow(x,3) for x in data_range])/(n*pow(data_std,3))
data_kurt=np.sum([pow(x,4) for x in data_range])/(n*pow(data_std,4))-3
print ('平均数:',data_mean)
print ('中位数:',data_median)
print ('方差:',data_sd)
print ('标准差:',data_std)
print('偏态系数:',data_sk)
print('峰态系数:',data_kurt)
get_data_describe(data1)
out:
平均数: 4.417739628040057
中位数: 4
方差: 7.9170529736942825
标准差: 2.8137258170785375
偏态系数: 0.5915855449527385
峰态系数: -0.6278342838815454
下一篇: HyperLogLog详解