import pandas as pd import numpy as np #Create a DataFrame df1 = { 'Subject':['semester1','semester2','semester3','semester4','semester1', 'semester2','semester3'], 'Score':[62,47,55,74,31,77,85]} df2 = { 'Subject':['semester1','semester2','semester3','semester4'], 'Score':[90,47,85,74]} df1 = pd.DataFrame(df1,columns=['Subject','Score']) df2 = pd.DataFrame(df2,columns=['Subject','Score']) print(df1) print(df2)
运行结果:
intersected_df = pd.merge(df1, df2, how='inner') print(intersected_df)
也可以指定求交集的列:
intersected_df = pd.merge(df1, df2, on=['Subject'], how='inner') print(intersected_df)
df2-df1:
set_diff_df = pd.concat([df2, df1, df1]).drop_duplicates(keep=False) print(set_diff_df)
df1-df2:
set_diff_df = pd.concat([df1, df2, df2]).drop_duplicates(keep=False) print(set_diff_df)
另一种求差集的方法是:
以df1-df2为例:
df1 = df1.append(df2) df1 = df1.append(df2) set_diff_df = df1.drop_duplicates(subset=['Subject', 'Score'],keep=False) print(set_diff_df)
得到的df1-df2结果是一样的:
到此这篇关于Pandas中两个dataframe的交集和差集的示例代码的文章就介绍到这了,更多相关Pandas dataframe交集差集内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。