【问题标题】:How many times a number appears in a numpy array一个数字在 numpy 数组中出现多少次
【发布时间】:2016-12-09 19:21:59
【问题描述】:

我需要找到一种方法来计算从 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。

【问题讨论】:

  • 首先,弄清楚你将如何手工完成。

标签: python python-3.x numpy count


【解决方案1】:

你应该可以很简单地得到这个:

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

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

np.count_nonzero(m == x)

万岁内置函数。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果您想从所有矩阵元素中获取频率,这里有一个使用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})
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • Counting a list 比这更容易:flat.count(x) 就足够了。
        • 另外,numpy 有一个 flatten: list(m.flatten()).count(x)
        • 我很好奇哪种方法更快,因为您仍然需要将其转换为列表@TemporalWolf
        • 通常内置函数比自定义函数快。欢迎您timeit
        • @TemporalWolf 这是不正确的,如果数组具有相关大小,NumPy 函数将比内置 Python 函数快得多。
        【解决方案5】:

        我会尝试使用参数 return_counts=True 的 numpy 唯一函数(请参阅: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])
        

        【讨论】:

        • 此代码不计算数组中给定的数字,而是计算所有唯一元素
        • 已更改。希望它现在有效。谢谢指出
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 2023-01-03
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多