numpy统计数组中元素的个数

提出问题

比如下面的numpy数组

import numpy as np

arr=np.random.randint(0,3,(2,3))
print(arr)

执行结果如下:

array([[0, 1, 1],
       [2, 0, 2]])

我们要看下该数组 有哪些值,以及 各个值出现的次数

解决问题

在numpy没有提供此函数,需要用到python的collections

import numpy as np
from collections import Counter

arr=np.random.randint(0,3,(2,3))

cnt=Counter(arr.flatten())

print(cnt)

执行结果:

Counter({0: 4, 1: 1, 2: 1})

注意:
多维数组,一定要先flatten(),否则报错

判断是否包含

cnt[0]

执行结果:

4

表示0这个数字出现4次

遍历

for k,v in cnt.items():
    print('元素 {} 出现 {} 次'.format(k,v))

执行结果:

元素 0 出现 4 次
元素 1 出现 1 次
元素 2 出现 1 次

原文出处:/show_1EF516wZhtvi.html