代码之家  ›  专栏  ›  技术社区  ›  Keshav M

统计列表列表中每个唯一项的出现次数

  •  1
  • Keshav M  · 技术社区  · 8 年前

    listoflist = [["A", "B", "A", "C", "D"], ["Z", "A", "B", "C"], ["D", "D", "X", "Y", "Z"]]
    

    listoflist 发生在。例如,“A”出现在两个子列表中,而“D”也出现在两个子列表中,即使它在中出现两次 listoflist[3]

    如何获得一个数据帧,该数据帧在一列中包含每个唯一元素,以及频率(每个唯一元素显示在其中的子列表的数量)?

    3 回复  |  直到 8 年前
        1
  •  3
  •   llllllllll    8 年前

    您可以使用: itertools.chain collections.Counter

    In [94]: import itertools as it
    
    In [95]: from collections import Counter
    
    In [96]: Counter(it.chain(*map(set, listoflist)))
    Out[96]: Counter({'A': 2, 'B': 2, 'C': 2, 'D': 2, 'X': 1, 'Y': 1, 'Z': 2})
    

    如@Jean-Fran§ois Fabre评论中所述,您还可以使用:

    In [97]: Counter(it.chain.from_iterable(map(set, listoflist)))
    Out[97]: Counter({'A': 2, 'B': 2, 'C': 2, 'D': 2, 'X': 1, 'Y': 1, 'Z': 2})
    
        2
  •  2
  •   Andrey Tyukin    8 年前

    本质上,你似乎想要

    Counter(x for xs in listoflist for x in set(xs))
    

    Counter .

    from collections import Counter
    
    listoflist = [["A", "B", "A", "C", "D"], ["Z", "A", "B", "C"], ["D", "D", "X", "Y", "Z"]]
    
    c = Counter(x for xs in listoflist for x in set(xs))
    
    print(c)
    

    结果:

    # output:
    # Counter({'B': 2, 'C': 2, 'Z': 2, 'D': 2, 'A': 2, 'Y': 1, 'X': 1})
    
        3
  •  1
  •   Scott Boston    8 年前

    另一种方法是使用熊猫:

    import pandas as pd
    
    df = pd.DataFrame(listoflist)
    df.stack().reset_index().groupby(0)['level_0'].nunique().to_dict()
    

    输出:

    {'A': 2, 'B': 2, 'C': 2, 'D': 2, 'X': 1, 'Y': 1, 'Z': 2}