我想计算 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
首先,我按 pair claim 事件分组,对于这些组中的每一个,我想计算 material1 和 material 2 列之间的匹配数
对于分组依据,我有 grouped = df.groupby(['claim', 'event'])
但是我不知道如何比较这两个新列。
它应该返回以下数据框:
claim event matches
A X 3
A Y 1
B Z 0
你知道怎么做吗?
最佳答案
使用isin
用于比较列和 groupby 与聚合 sum
的列,最后转换为 int
和 reset_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
中它应该更慢:
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
关于python - Pandas 和 groupby 计算两个不同列中的匹配项数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693482/