python统计数组中出现次数最多的元素 |
您所在的位置:网站首页 › python统计次数用什么函数 › python统计数组中出现次数最多的元素 |
python查找数组中出现次数最多的元素
方法1-np.argmax(np.bincount())
array = [0,1,2,2,3,4,4,4,5,6]
print(np.bincount(array))
#[1 1 2 1 3 1 1]
print(np.argmax(np.bincount(array)))
#4
np.argmax:就是返回数组中最大值对应的下标, np.bincount:首先找到数组最大值max,然后返回0~max的各个数字出现的次数,只能处理不含负数的集合 方法2-Counter().most_common from collections import Counter array = [0,1,2,2,3,4,4,4,5,6] print(Counter(array)) #Counter({4: 3, 2: 2, 0: 1, 1: 1, 3: 1, 5: 1, 6: 1}) print(Counter(array).most_common(1)[0][0]) #4Counter用来对数组中元素出现次数进行统计,然后通过most_common函数找到出现次数最多的元素。这种方法对于数组就没有过多限制,甚至是各种类型元素混合的数组也可以。数组只能是array,不能是ndarray. from collections import Counter array = [0,1,2,2,3,4,4,4,5,6,'aswd'] print(Counter(array)) print(Counter(array).most_common(1)[0][0]) #Counter({4: 3, 2: 2, 0: 1, 1: 1, 3: 1, 5: 1, 6: 1, 'aswd': 1}) #4 方法三-- 自己数各个元素出现的次数然后找到出现次数最多的元素 appear_times = {} for label in [1,1,2,3,4,5,5,5]: if label in appear_times: appear_times[label] += 1 else: appear_times[label] = 1 most_common = max(appear_times, key=lambda x: appear_times[x]) print(appear_times) print(most_common) #{1: 2, 2: 1, 3: 1, 4: 1, 5: 3} #5这里需要注意的是appear_times是一个列表,用max求最大值默认情况返回value值(出现次数)最大的key值(元素),而不是value值,这里max函数中的参数key(和前面说的key不是一个东西)是指定寻找最大值的方式,在我们这个问题这里其实不需要这个参数,不过为了便于理解我还是写上了,对max函数key参数更深入的理解可以参考下面的例子: 复制代码 print(max('ahecsc', 'bfsacg', 'aaaaaz', key=lambda x: x[0])) print(max('ahecsc', 'bfsacg', 'aaaaaz', key=lambda x: x[3])) print(max('ahecsc', 'bfsacg', 'aaaaaz', key=lambda x: x[5])) #bfsacg #ahecsc #aaaaaz同样的数据,key参数不同,结果不同,第一种情况是以数据的第一个位置元素的大小关系排序,并返回排序结果最大的数据(‘b’>‘a’>‘a’,返回’b’所在的’bfsacg’);第二种情况类似(‘c’>‘a’>‘a’,返回’c’所在的’ahecsc’);第三种情况(‘z’>‘g’>‘c’,返回’z’所在的’aaaaaz’) 文章转载出处:https://www.cnblogs.com/RB26DETT/p/11518589.html |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |