简体   繁体   English

如何计算 dataframe 组中行的唯一组合?

[英]How to count unique combinations of rows in dataframe group by?

I would like to use pandas groupby to count the occurrences of a combination of animals on each farm (denoted by the farm_id).我想使用 pandas groupby 来计算每个农场上动物组合的出现次数(由 farm_id 表示)。 I am trying to count the number of farms with each type of animal combination.我正在尝试计算每种动物组合的农场数量。

The desired output would be something like this:所需的 output 将是这样的:

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

For the following dataframe:对于以下 dataframe:

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

Notice the order the animals appear does not matter.注意动物出现的顺序并不重要。

I have tried this:我试过这个:

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]

Which gives me the combinations, but (1) the ordering is taken into account and (2) I'm not sure how to generate the count as a separate column.这给了我组合,但是(1)考虑了排序和(2)我不确定如何将计数生成为单独的列。

Try:尝试:

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()

Count the nummber of occurences计算出现次数

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']
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())

The key to this solution is making the list of animals hashable by using a tuple and then sorting that tuple so that we can count the number of combo occurrences.该解决方案的关键是通过使用元组使动物列表可散列,然后对该元组进行排序,以便我们可以计算组合出现的次数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM