python - 一个数字在 numpy 数组中出现了多少次

标签 python python-3.x numpy count

我需要找到一种方法来计算从 0 到 9 的每个数字在使用 np.random.randint()

创建的随机矩阵中出现的次数
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)

例如,如果矩阵的长度 = 4

  • [[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]

数字 4 出现了多少次?它应该返回 5。

最佳答案

你应该能够很简单地得到这个:

list(m.flatten()).count(x)

另一个可能更快的选择是使用 numpy 内置 count_nonzero() :

np.count_nonzero(m == x)

内置函数万岁。

关于python - 一个数字在 numpy 数组中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067471/

相关文章:

python - PyTorch 中 tensor.permute 和 tensor.view 的区别?

python - 从 C++ dll 到 Python 的指针 vector 上返回指针

python - "pip install line_profiler"失败

Python Boto Dynamodb 对范围键的小记录集检索性能非常慢

python-3.x - 如何在每组pandas groupby对象中添加标志列

python - Scipy:数组中的稀疏指示矩阵

python - jsonResponse = r.json() 名称错误 : name 'r' is not defined

python - 使用 yield from 时协程在哪个事件循环中运行?

python-3.x - 使用 Python 在图像上应用过滤器

python - 将一行中的每个元素相乘并在同一数据框中附加新列?