比较数据帧并输出计数匹配数 [英] Compare dataframes and output the numbers of count matches
本文介绍了比较数据帧并输出计数匹配数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算一个数据帧在另一个数据帧中的出现次数,并输出匹配计数.
I would like to count occurences of one dataframe in another dataframe and output the counts of matches.
df
group1 group2
0 orange orange
1 apple apple
2 banana pear
3 banana banana
.
fruit_df
fruits
0 orange
1 banana
所以:
groups = ["group1", "group2"]
matrix = pd.DataFrame()
for group in groups:
out = fruit_df["fruits"].isin(df[group]).astype(int)
matrix = pd.concat([matrix, out], axis = 1)
matrix.columns = groups
matrix = matrix.rename(index = fruit_df["fruits"])
结果:
matrix
group1 group2
orange 1 1
banana 1 1
我想要的是:
matrix
group1 group2
orange 1 1
banana 2 1
推荐答案
这是您可以尝试的方法之一
Here's one of the way you could try
temp_df = pd.melt(df, var_name='group', value_name='fruits')
temp_df['count'] = 1
df_count = temp_df.pivot_table(index=['fruits'], columns=['group'], values='count', aggfunc=np.sum).reset_index()
matrix = fruits_df.merge(df_count)
matrix.set_index('fruits')
print(matrix)
结果是
这篇关于比较数据帧并输出计数匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文