Pandas and groupby count the number of matches in two different columns

不打扰是莪最后的温柔 提交于 2019-12-05 18:19:33

Use isin for compare columns and groupby by columns with aggregate sum, last cast to int and reset_index for columns from MultiIndex:

a = (df['material1'].isin(df['material2']))
df = a.groupby([df['claim'], df['event']]).sum().astype(int).reset_index(name='matches')

Solution with assign to new column:

df['matches'] = df['material1'].isin(df['material2']).astype(int)
df = df.groupby(['claim', 'event'])['matches'].sum().reset_index()

Solutions by @Wen, thank you:

df['matches'] = df['material1'].isin(df['material2']).astype(int)
df = df.groupby(['claim', 'event'], as_index=False)['matches'].sum()

I think it should be slowier in larger DataFrames:

df = (df.groupby(['claim', 'event'])
                  .apply(lambda x : x['material1'].isin(x['material2']).astype(int).sum())
                  .reset_index(name='matches'))

print (df)
  claim event  matches
0     A     X        3
1     A     Y        1
2     B     Z        0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!