【问题标题】:Is there a "freq" function in numpy/python? [duplicate]numpy/python 中是否有“freq”函数? [复制]
【发布时间】:2013-04-01 12:12:18
【问题描述】:

假设你有:

arr = np.array([1,2,1,3,3,4])

是否有返回最频繁元素的内置函数?

【问题讨论】:

  • 如果所有元素都是整数,则使用np.bincount

标签: python numpy


【解决方案1】:

是的,Python 的collections.Counter 直接支持查找最常见的元素:

>>> from collections import Counter

>>> Counter('abracadbra').most_common(2)
[('a', 4), ('r', 2)]

>>> Counter([1,2,1,3,3,4]).most_common(2)
[(1, 2), (3, 2)]

使用 numpy,您可能希望以 histogram() functionbincount() function 开头。

使用 scipy,您可以使用 mstats.mode 搜索模态元素。

【讨论】:

    【解决方案2】:

    pandas 模块在这里也可能会有所帮助。 pandas 是一个简洁的 python 数据分析包,也支持这个问题。

    import pandas as pd 
    arr = np.array([1,2,1,3,3,4])
    arr_df = pd.Series(arr) 
    value_counts = arr_df.value_counts()
    most_frequent = value_counts.max()
    

    这会返回

    > most_frequent 
    2 
    

    【讨论】:

      【解决方案3】:

      这适用于任何类型,无论是否为整数,并且返回始终是一个 numpy 数组:

      def most_common(a, n=1) :
          if a.dtype.kind not in 'bui':
              items, _ = np.unique(a, return_inverse=True)
          else:
              items, _ = None, a
          counts = np.bincount(_)
          idx = np.argsort(counts)[::-1][:n]
          return idx.astype(a.dtype) if items is None else items[idx]
      
      >>> a = np.fromiter('abracadabra', dtype='S1')
      >>> most_common(a, 2)
      array(['a', 'r'], 
            dtype='|S1')
      >>> a = np.random.randint(10, size=100)
      >>> a
      array([0, 0, 0, 9, 3, 9, 1, 2, 6, 3, 0, 4, 3, 2, 4, 7, 2, 8, 8, 2, 9, 7, 0,
             3, 5, 2, 5, 0, 4, 2, 4, 7, 8, 5, 4, 0, 1, 6, 1, 0, 2, 0, 5, 1, 3, 8,
             8, 6, 3, 5, 4, 3, 3, 5, 0, 7, 3, 0, 2, 5, 4, 2, 4, 2, 8, 1, 4, 4, 7,
             4, 4, 3, 7, 4, 0, 1, 0, 8, 8, 1, 1, 2, 1, 4, 2, 5, 1, 0, 7, 2, 0, 0,
             0, 8, 9, 9, 8, 1, 3, 8])
      >>> most_common(a, 5)
      array([0, 4, 2, 8, 3])
      

      【讨论】:

        猜你喜欢
        • 2019-08-17
        • 1970-01-01
        • 2013-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多