一个numpy数组中一个数字出现的次数

7

我需要找到一种方法来计算在使用np.random.randint()创建的随机矩阵中,数字0到9出现的次数。

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。

首先,手动尝试解决问题。 - Ignacio Vazquez-Abrams
5个回答

10
你应该能够很容易地实现这个:
list(m.flatten()).count(x)

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

np.count_nonzero(m == x)

太棒了,内置函数。


3
您可以使用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,您可以对数组项进行求和以获得预期项的数量。


2
如果您想从所有矩阵元素中获取频率,这里有一个简单的解决方案,使用numpy.ndarray.flatten和collections.Counter:

(如果要查看文档,请点击以下链接:numpy.ndarray.flattencollections.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})

1
你可以将矩阵压平,然后使用列表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)

2
计算列表的元素个数比这更容易:flat.count(x)就足够了。 - TemporalWolf
2
另外,numpy有一个flatten函数:list(m.flatten()).count(x) - TemporalWolf
我很好奇哪种方法更快,因为你仍然需要将其转换为列表 @TemporalWolf - rofls
通常内置函数比自定义函数更快。欢迎使用 timeit 进行测试。 - TemporalWolf
@TemporalWolf 这是不正确的,如果数组大小相关,NumPy函数将比内置的Python函数快得多。 - Daniel
@Daniel 我正在包含numpy内置函数(如flatten),并将它们与rofls的自定义列表推导式解决方案进行比较。 - TemporalWolf

0
我会尝试使用numpy的unique函数,并带有参数return_counts=True(请参见: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])

已经修改了。希望现在可以正常工作。感谢您指出问题。 - Shaig Hamzaliyev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接