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])
#4

Counter用來對數組中元素出現次數進行統計,然後通過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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章