繁体   English   中英

Pandas和groupby计算两个不同列中的匹配数

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

我想计算一个pandas数据帧中groupby之后的匹配数。

claim   event   material1   material2
A       X       M1          M2
A       X       M2          M3
A       X       M3          M0
A       X       M4          M4
A       Y       M5          M5
A       Y       M6          M0
B       Z       M7          M0
B       Z       M8          M0

首先,我按对索赔事件进行分组,对于每个组,我想计算列material1和material 2之间的匹配数

对于分组,我已经grouped = df.groupby(['claim', 'event'])但后来我不知道如何比较两个新列。

它应该返回以下数据帧:

claim   event   matches
A       X       3          
A       Y       1          
B       Z       0          

你知道怎么做吗?

使用isin通过与聚合列比较列和GROUPBY sum ,去年投地intreset_index从列MultiIndex

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

分配给新列的解决方案:

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

@Wen解决方案,谢谢:

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

我认为在较大的DataFrame它应该更DataFrame

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

暂无
暂无

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

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