Python 如何计算数据帧组中的行的唯一组合?
我想使用pandas groupby来计算每个农场上动物组合的出现次数(由农场id表示)。我试图计算每种动物组合的农场数量 所需的输出如下:Python 如何计算数据帧组中的行的唯一组合?,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我想使用pandas groupby来计算每个农场上动物组合的出现次数(由农场id表示)。我试图计算每种动物组合的农场数量 所需的输出如下: Out[6]: combo count 0 cow 1 1 [cow, chicken] 1 2 [cow, pig, chicken] 2 对于以下数据帧: df = pd.DataFrame([['cow',0],['chicken',
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)我不确定如何将计数作为单独的列生成。试试:
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']
这个解决方案的关键是使用一个元组对动物列表进行哈希处理,然后对该元组进行排序,这样我们就可以计算组合出现的次数。Nice!有没有办法将字典转换为列?如果计数是数据框中的一列,那就更方便了。@BenjaminLatimer-检查我的更新-我可以在Nev的答案和我的答案上重复输入,而无需使用
计数器
。Cheers@BenjaminLatimer-见修订后的答案。
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
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