Numpy求均值、中位数、众数的方法

首先需要数据源,这里随便写了一个:

nums = [1,2,3,4]

求均值和中位数均可以使用numpy库的方法:

import numpy as np
 #均值
np.mean(nums)
#中位数
np.median(nums)

求众数方法一:

在numpy中没有直接的方法,但是也可以这样实现:

import numpy as np
#bincount():统计非负整数的个数,不能统计浮点数 counts
= np.bincount(nums) #返回众数 np.argmax(counts)

求众数方法二——直接利用scipy下stats模块【推荐】:

from scipy import stats
 stats.mode(nums)[0][0]

方法二可以用于浮点数

猜你喜欢

转载自www.cnblogs.com/lijinze-tsinghua/p/9905882.html