【问题标题】:Python - Count most frequent elements in list of same lengthPython - 计算相同长度列表中最常见的元素
【发布时间】:2019-07-21 03:21:36
【问题描述】:

过去几个小时我一直在寻找这个问题的答案,但没有找到我想要的答案,所以我决定改为在这里提问。

所以,假设我有一个长度相同的数据列表,例如;

0004000000350
0000090033313
0004000604363
040006203330b
0004000300a3a
0004000403833
00000300333a9
0004000003a30

在每个位置匹配出现次数最多的字符的最有效方法是什么。

示例输出类似于:

0 0 0 4 0 0 0 0 0 3 3 3 3



编辑:感谢您的回答,给了我想要的东西! :)



编辑 2:我想补充一下这个问题,因为它可能是最简单的解决方法。使用建议的答案,您将如何添加总数以及某种百分比?由于它是一个庞大的数据集,仅最常见的事件并不像我希望的那样清晰。

【问题讨论】:

  • 为什么预期输出的第四个元素是4而不是0?
  • 在示例数据集中,位置 4 中出现频率最高的字符是 4. 4 出现 5 次,而 0 出现 3 次。

标签: python string frequency


【解决方案1】:

由于没有人使用过pandas,所以使用pandas可以轻松高效地实现这一点

a = """0004000000350
0000090033313
0004000604363
040006203330b
0004000300a3a
0004000403833
00000300333a9
0004000003a30"""

import pandas as pd
df = pd.DataFrame([list(j) for j in a.strip().split('\n')])
result =  df.mode().to_string(header=None,index=None)
print(result)

""" output 
 0  0  0  4  0  0  0  0  0  3  3  3  3
"""

【讨论】:

    【解决方案2】:
    from collections import Counter
    ''.join(Counter(i).most_common(1)[0][0] for i in zip(*l))
    

    l 是您的字符串列表。

    【讨论】:

    • expected str instance, tuple found 缺少[0]
    【解决方案3】:

    您开始使用zip 来交错每个字符串中处于相同相对位置的字符。然后使用 scipy.stats.mode 获取每个元组的模式,并连接生成器表达式的结果字符串:

    l = ['0004000000350', '0000090033313', '0004000604363', '040006203330b', 
         '0004000300a3a', '0004000403833', '00000300333a9', '0004000003a30']
    
    from scipy.stats import mode
    ''.join(mode(i).mode[0] for i in list(zip(*l)))
    

    输出

    '0004000003333'
    

    【讨论】:

      【解决方案4】:

      如果不导入,我会这样做:

      data = [
      "0004000000350",
      "0000090033313",
      "0004000604363",
      "040006203330b",
      "0004000300a3a",
      "0004000403833",
      "00000300333a9",
      "0004000003a30",
      ]
      
      # return the most common elemebt in an iterable
      most_common = lambda ite: max(ite, key=ite.count)  
      
      # print the most_common in each columns
      print(map(most_common, zip(*data)))
      
      # ['0', '0', '0', '4', '0', '0', '0', '0', '0', '3', '3', '3', '3']
      

      【讨论】:

      • 可能值得注意的是 maxkey 是 O(n²),不过。
      【解决方案5】:

      压缩字符串列表以“转置”它们以在同一迭代器中呈现列,在它们上应用collections.Counter,并使用most_common 方法,删除不需要的数据

      data="""0004000000350
      0000090033313
      0004000604363
      040006203330b
      0004000300a3a
      0004000403833
      00000300333a9
      0004000003a30"""
      
      import collections
      
      counts = [collections.Counter(x).most_common(1)[0][0] for x in zip(*data.splitlines())]
      

      这会产生:

      ['0', '0', '0', '4', '0', '0', '0', '0', '0', '3', '3', '3', '3']
      

      (如果需要,使用 "".join(counts) 加入字符以重新创建字符串)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-14
        • 1970-01-01
        • 2015-02-18
        • 2019-06-02
        • 1970-01-01
        • 1970-01-01
        • 2016-07-21
        • 2010-12-03
        相关资源
        最近更新 更多