python使用Counter實現二維陣列按列(行)統計元素出現個數
阿新 • • 發佈:2018-11-05
主要是用到了 collections 裡面的Counter函式
import numpy as np from collections import Counter rows=10 cols=9 arr=np.random.random_integers(1,10,(10,9))#生成整數陣列 print("二維陣列元素:",arr) result = [Counter(arr[:, i]).most_common(1)[0] for i in range(cols)] print("按列統計的結果為:",result)#顯示的結果中第一個是數字,第二個是這個數字出現的次數 result = [Counter(arr[i, :]).most_common(1)[0] for i in range(rows)] print("按行統計的結果為:",result) -------------------------------------------------------------------------------- 二維陣列元素: [[ 9 5 10 8 6 9 4 7 9] [ 4 9 5 3 9 9 3 2 5] [ 6 3 3 8 7 1 9 1 5] [ 8 10 6 8 3 10 7 10 7] [ 8 6 1 9 4 10 3 4 4] [ 2 5 9 8 7 6 5 6 3] [ 4 1 4 4 8 9 4 10 6] [ 9 5 8 8 10 2 1 2 2] [ 2 1 9 5 3 7 8 3 4] [ 6 9 7 10 3 2 10 8 2]] 按列統計的結果為: [(9, 2), (5, 3), (9, 2), (8, 5), (3, 3), (9, 3), (4, 2), (2, 2), (5, 2)] 按行統計的結果為: [(9, 3), (9, 3), (3, 2), (10, 3), (4, 3), (5, 2), (4, 4), (2, 3), (3, 2), (10, 2)]