一个数字在numpy数组中出现多少次 [英] How many times a number appears in a numpy array
本文介绍了一个数字在numpy数组中出现多少次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到一种方法来计算从0到9的每个数字出现在使用 np.random.randint()
I need to find a way to count how many times each number from 0 to 9 appears in a random matrix created using np.random.randint()
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
例如,如果矩阵的长度= 4
For example if length of matrix = 4
- [[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]
数字4出现几次?它应该返回5.
How many times does the number 4 appear? It should return 5.
推荐答案
您应该可以很简单地获得它:
You should be able to get this pretty simply:
list(m.flatten()).count(x)
另一个可能更快的选项是使用内置的numpy count_nonzero()
:
Another option which is probably faster, is to use the numpy builtin count_nonzero()
:
np.count_nonzero(m == x)
Hooray内置函数.
Hooray builtin functions.
这篇关于一个数字在numpy数组中出现多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文