In [4]: import scipy.stats
In [5]: a = numpy.random.randint(1,10,(1000,1000))
In [6]: %timeit scipy.stats.mode(a)
10 loops, best of 3: 41.6 ms per loop
In [7]: %timeit mode(a)
10 loops, best of 3: 46.7 ms per loop
In [8]: a = numpy.random.randint(1,500,(1000,1000))
In [9]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 1.01 s per loop
In [10]: %timeit mode(a)
10 loops, best of 3: 80 ms per loop
In [11]: a = numpy.random.random((200,200))
In [12]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 3.26 s per loop
In [13]: %timeit mode(a)
1000 loops, best of 3: 1.75 ms per loop
import numpy as np
from collections import Counter
nparr = np.arange(10)
nparr[2] = 6
nparr[3] = 6 #6 is now the mode
mode = Counter(nparr).most_common(1)
# mode will be [(6,3)] to give the count of the most occurring value, so ->
print(mode[0][0])
对于多维数组(差别不大):
import numpy as np
from collections import Counter
nparr = np.arange(10)
nparr[2] = 6
nparr[3] = 6
nparr = nparr.reshape((10,2,5)) #same thing but we add this to reshape into ndarray
mode = Counter(nparr.flatten()).most_common(1) # just use .flatten() method
# mode will be [(6,3)] to give the count of the most occurring value, so ->
print(mode[0][0])
4 回答
检查scipy.stats.mode()(灵感来自@ tom10的评论):
输出:
如您所见,它既返回模式又返回计数 . 您可以直接通过
m[0]
选择模式:输出:
这是一个棘手的问题,因为沿着轴计算模式并不多 . 解决方案对于1-D阵列是直接的,其中
numpy.bincount
是方便的,numpy.unique
与return_counts
arg为True
. 我看到的最常见的n维函数是scipy.stats.mode,虽然它非常慢 - 特别是对于具有许多唯一值的大型数组 . 作为一个解决方案,我开发了这个功能,并大量使用它:结果:
一些基准:
编辑:提供更多的背景和修改方法,以提高内存效率
扩展this method,应用于查找数据模式,您可能需要实际数组的索引,以查看该值与分布中心的距离 .
记得在len(np.argmax(计数))> 1时丢弃该模式,同时为了验证它是否实际代表您的数据的中心分布,您可以检查它是否在标准偏差区间内 .
我认为一种非常简单的方法是使用Counter类 . 然后,您可以使用Counter实例的most_common()函数,如here所述 .
对于一维数组:
对于多维数组(差别不大):
这可能是也可能不是有效的实现,但它很方便 .