首页 » Python » python 实现极差、方差、标准差、变异系数

python 实现极差、方差、标准差、变异系数

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import pandas as pd
import numpy as np
from scipy import stats
from numpy.random import normal,randint
data6 = randint(0,10,size=12)  # 从几开始,从几结束,生成多少个  这里是创造10个从0(包含)开始,从10结束(不包含10)的随机数据,数字代表类别
print(data6)

# 极差
def cal_ptp(num1):
    return max(num1) - min(num1)


print(cal_ptp(data6))  # [0 9 9 8 4 5 4 3 1 6 0 1]  9
print(np.ptp(data6))

# 方差
def cal_var(num1):
    num1_mean = sum(num1)/len(num1)
    res = 0
    for num in num1:
        res += (num - num1_mean) ** 2
    res = res / len(num1)
    return res


print(cal_var(data6))  # [0 5 3 3 1 1 2 6 4 4 9 6] 6.055555555555556
print(np.var(data6))


# 标准差
def cal_std(num1):
    return cal_var(num1) ** 0.5


print(cal_std(data6))  # [5 0 1 5 1 0 1 3 1 4 1 9] 2.5967394084804805
print(np.std(data6))


# 变异系数

def cal_cv(num1):
    num1_mean = sum(num1)/len(num1)
    return cal_std(num1)/num1_mean
print(cal_cv(data6))  # [4 6 7 7 3 0 5 9 2 7 0 5]  0.600550711451409
print(np.std(data6)/np.mean(data6))

原文链接:python 实现极差、方差、标准差、变异系数,转载请注明来源!

0