[英]How many times a number appears in a numpy array
我需要找到一种方法来计算使用np.random.randint()
创建的随机矩阵中从 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
数字 4 出现了多少次? 它应该返回 5。
你应该能够很简单地得到这个:
list(m.flatten()).count(x)
另一个可能更快的选项是使用 numpy 内置count_nonzero()
:
np.count_nonzero(m == x)
万岁内置函数。
您可以使用sum
函数:
In [52]: m = np.random.randint(0,9,(4,4))
In [53]: m
Out[53]:
array([[8, 8, 2, 1],
[2, 7, 1, 2],
[8, 6, 8, 7],
[5, 2, 5, 2]])
In [56]: np.sum(m == 8)
Out[56]: 4
m == 8
将为每个 8 返回一个包含 True 的布尔数组,然后由于 python 将 True 评估为 1,您可以对数组项求和以获得预期项的数量。
如果你想从所有矩阵元素中获取频率,这里有一个使用numpy.ndarray.flatten和collections.Counter的简单解决方案:
import numpy as np
import collections
p = int(input("Length of matrix: "))
m = np.random.randint(0, 9, (p, p))
print(m)
print(collections.Counter(m.flatten()))
例如,当 p=3 时,您会得到如下结果:
[[8 4 8]
[5 1 1]
[1 1 1]]
Counter({1: 5, 8: 2, 4: 1, 5: 1})
您可以展平矩阵,然后使用 list count()
方法:
from collections import Counter
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
flat = [item for sublist in m for item in sublist]
flat.count(4)
我会尝试使用参数 return_counts=True 的 numpy unique 函数(参见: https ://numpy.org/doc/stable/reference/generated/numpy.unique.html)。
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
# print(m)
un, nm = np.unique(m, return_counts = True)
# if number that you are looking for is 1 then:
print(nm[un==1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.