【问题标题】:Create a dictionary of category counts for a pandas column为 pandas 列创建类别计数字典
【发布时间】:2018-07-30 20:53:48
【问题描述】:

我有以下数据框:

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}

除了逐行循环整个数据框,有没有更优雅的方式来获取结果?谢谢!

【问题讨论】:

  • 您是否可以选择在保持相同数据的同时以不同方式构建数据框?

标签: python python-3.x pandas dictionary counter


【解决方案1】:

collections.Counteritertools.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】:

    只需使用内置函数即可:

    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】:

      是的,你可以使用计数器

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-22
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        相关资源
        最近更新 更多