【问题标题】:pandas: How to get the most frequent item in pandas series?pandas:如何获取pandas系列中出现频率最高的item?
【发布时间】:2019-02-01 23:12:57
【问题描述】:

如何获得pandas 系列中最常见的项目?

考虑系列s

s = pd.Series("1 5 3 3 3 5 2 1 8 10 2 3 3 3".split()).astype(int)

返回值应该是3

【问题讨论】:

    标签: python python-3.x pandas series


    【解决方案1】:

    您可以只使用pd.Series.mode 并提取第一个值:

    res = s.mode().iloc[0]
    

    这不一定是低效的。与往常一样,用您的数据进行测试,看看适合什么。

    import numpy as np, pandas as pd
    from scipy.stats.mstats import mode
    from collections import Counter
    
    np.random.seed(0)
    
    s = pd.Series(np.random.randint(0, 100, 100000))
    
    def jez_np(s):
        _, idx, counts = np.unique(s, return_index=True, return_counts=True)
        index = idx[np.argmax(counts)]
        val = s[index]
        return val
    
    def pir(s):
        i, r = s.factorize()
        return r[np.bincount(i).argmax()]
    
    %timeit s.mode().iloc[0]                 # 1.82 ms
    %timeit pir(s)                           # 2.21 ms
    %timeit s.value_counts().index[0]        # 2.52 ms
    %timeit mode(s).mode[0]                  # 5.64 ms
    %timeit jez_np(s)                        # 8.26 ms
    %timeit Counter(s).most_common(1)[0][0]  # 8.27 ms
    

    【讨论】:

      【解决方案2】:

      使用value_counts 并通过index 选择第一个值:

      val = s.value_counts().index[0]
      

      Counter.most_common:

      from collections import Counter
      
      val = Counter(s).most_common(1)[0][0]
      

      或者numpy的解决方案:

      _, idx, counts = np.unique(s, return_index=True, return_counts=True)
      index = idx[np.argmax(counts)]
      val = s[index]
      

      【讨论】:

      • series.mode() 怎么样?
      • @anky_91 - 很慢:(
      【解决方案3】:

      pandas.factorizenumpy.bincount

      这与@jezrael 的 Numpy 答案非常相似。区别在于使用factorize 而不是numpy.unique

      • factorize 返回整数分解和唯一值
      • bincount 计算每个唯一值的数量
      • argmax 确定哪个 bin 或因素是最频繁的
      • 使用从 argmax 返回的 bin 的位置来引用唯一值数组中出现频率最高的值

      i, r = s.factorize()
      r[np.bincount(i).argmax()]
      
      3
      

      【讨论】:

      • 是的。它应该是。老实说,尽管直到刚才我才注意到您的 Numpy 回答。我将删除此内容并对您的评论发表评论。
      • 我刚刚从这个版本中添加了计时,看起来相当快但似乎没有击败pd.Series.mode
      【解决方案4】:
      from scipy import stats
      import pandas as pd
      x=[1,5,3,3,3,5,2,1,8,10,2,3,3,3]
      data=pd.DataFrame({"values":x})
      
      
      print(stats.mode(data["values"]))
      
      output:-ModeResult(mode=array([3], dtype=int64), count=array([6]))
      

      【讨论】:

        猜你喜欢
        • 2020-03-26
        • 2018-03-24
        • 2014-12-20
        • 2018-02-05
        • 2020-07-25
        • 2020-05-19
        • 2018-07-13
        • 1970-01-01
        • 2022-11-28
        相关资源
        最近更新 更多