【问题标题】:How to count unique combinations of rows in dataframe group by?如何计算数据框组中行的唯一组合?
【发布时间】:2020-06-20 14:02:03
【问题描述】:

我想使用 pandas groupby 来计算每个农场中动物组合的出现次数(由 farm_id 表示)。我正在尝试计算每种动物组合的农场数量。

想要的输出应该是这样的:

Out[6]: 
                 combo  count
0                  cow      1
1       [cow, chicken]      1
2  [cow, pig, chicken]      2

对于以下数据框:

df = pd.DataFrame([['cow',0],['chicken',0],
                   ['cow',1],
                   ['chicken',3],['pig',3],['cow',3],
                   ['pig',4],['cow',4],['chicken',4]]
                   ,columns=['animals','farm_id'])

df
Out[4]: 
   animals  farm_id
0      cow        0
1  chicken        0
2      cow        1
3  chicken        3
4      pig        3
5      cow        3
6      pig        4
7      cow        4
8  chicken        4

注意动物出现的顺序并不重要。

我试过这个:

df.groupby('farm_id').agg({'animals':'unique'})
Out[7]: 
                     animals
farm_id                     
0             [cow, chicken]
1                      [cow]
3        [chicken, pig, cow]
4        [pig, cow, chicken]

这给了我组合,但 (1) 考虑了排序以及 (2) 我不确定如何将计数生成为单独的列。

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    试试:

    import pandas as pd
    from collections import Counter
    
    df_1=df.groupby('farm_id')['animals'].unique().apply(list).apply(lambda x: sorted(x)).reset_index()
    

    计算出现次数

    dict=Counter([tuple(i) for i in df_1['animals']])
    
    counter_df=pd.DataFrame.from_dict(dict, orient='index').reset_index()
    counter_df.columns=['combo','count']
    

    【讨论】:

    • 不错!有没有办法将字典转换为列?如果计数是数据框中的一列会更方便。
    • @BenjaminLatimer - 检查我的更新 - 我能够在不使用 Counter 的情况下重复 Nev 的答案和我的答案。干杯
    • @BenjaminLatimer - 查看修改后的答案。
    【解决方案2】:
    df = df.groupby('farm_id')['animals'].unique().apply(lambda x: tuple(sorted(x))).reset_index().rename(columns={'farm_id':'count'})
    print(df.groupby('animals').count())
    

    此解决方案的关键是通过使用元组使动物列表可散列,然后对该元组进行排序,以便我们可以计算组合出现的次数。

    【讨论】:

      【解决方案3】:
      import pandas as pd
      df = pd.DataFrame([['cow',0],['chicken',0],
                     ['cow',1],
                     ['chicken',3],['pig',3],['cow',3],
                     ['pig',4],['cow',4],['chicken',4]]
                     ,columns=['animals','farm_id'])
      df  = df.sort_values(['animals','farm_id'])
      df = df.groupby('farm_id').agg({'animals':'unique'})
      df['animals'] = df['animals'].astype(str)
      df2 = pd.DataFrame(df.animals.value_counts())
      df = pd.merge(df, df2, left_on = 'animals', right_index = True,how = 'left')
      df.columns = ['animal_combination','count']
      df
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-09
        • 2020-02-12
        • 2018-12-18
        • 2019-05-16
        • 1970-01-01
        相关资源
        最近更新 更多