python使用Counter实现二维数组按列(行)统计元素出现个数

版权声明:转载注明出处 https://blog.csdn.net/york1996/article/details/83339571

主要是用到了 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)]

猜你喜欢

转载自blog.csdn.net/york1996/article/details/83339571