代码之家  ›  专栏  ›  技术社区  ›  Edamame

为pandas列创建类别计数字典

  •  1
  • Edamame  · 技术社区  · 6 年前

    我有以下数据框:

    person    pets
    John     [cat, dog]
    Amy      [bird, fish, cat]
    Dave     [cow, horse, dog]
    Mary     [lamb, camel, rino]
    Jim      [bird, dog]
    

    我想把 pets 列以查找每种宠物类型的事件。这个例子的预期答案应该是:

    {cat: 2, dog: 3, bird:2, fish:1, cow:1, horse:1, lamb: 1, camel: 1, rino:1}
    

    除了一行一行地循环整个数据帧,是否有更优雅的方法来获得结果?谢谢!

    3 回复  |  直到 6 年前
        1
  •  1
  •   jpp    6 年前

    使用 collections.Counter 具有 itertools.chain :

    from collections import Counter
    from itertools import chain
    
    res = Counter(chain.from_iterable(df['pets']))
    
    print(res)
    
    Counter({'dog': 3, 'cat': 2, 'bird': 2, 'fish': 1, 'cow': 1,
             'horse': 1, 'lamb': 1, 'camel': 1, 'rhino': 1})
    
        2
  •  1
  •   Onyambu    6 年前

    通过使用内置功能,您可以:

    a = [j for i in df['pets'] for j in i]
    
    {i:a.count(i) for i in set(a)}
    
    {'fish': 1,'bird': 2,'dog': 3,'camel': 1,'cat': 2,'lamb': 1,'horse': 1,'cow': 1,'rhino': 1}
    
        3
  •  0
  •   Yuca    6 年前

    是的,你可以用柜台

    import collections
    import pandas
    d = {'person': ['John', 'Amy', 'Dave', 'Mary','Jim'], 'pets': [['cat','dog'], ['bird','fish','cat'],['cow','horse','dog'], ['lamb', 'camel' , 'rhino'],['bird','dog']]}
    df1 = pd.DataFrame.from_dict(d)
    collections.Counter(sum(df1.pets,[]))
    

    以一种良好的格式输出

    counts = pd.DataFrame.from_dict(collections.Counter(sum(df1.pets,[])),orient='index')
    

    输出:

    0
    cat 2
    dog 3
    bird    2
    fish    1
    cow 1
    horse   1
    lamb    1
    camel   1
    rhino   1