首先先造两个DataFrame来做示例。
import pandas as pd
a0={"number":range(10),"letter":["a","a","b","b","c","f","f","e","h","w"]}
a=pd.DataFrame(a0)
b0={"number":range(15),"letter":["b","a","t","b","r","f","g","e","j","w","t","h","i","y","u"]}
b=pd.DataFrame(b0)
看一下两个DataFrame的样子
a b
关于差集,我们是要去除两个DataFrame中公共的部分,因此我的想法是:
(1)先将两个DataFrame融合为一个DataFrame;
(2)去掉当中公共的部分(使用drop_duplicates去重)。
下面来看一下代码:
c=a.append(b) c.drop_duplicates(keep=False,inplace=True) c.reset_index() 这里想要说明的是,drop_duplicates当中的参数keep=False,意为重复项全部删除,它还有keep="first"与keep="last",分别对应在有多项重复时,保留第一项(或最后一项)。具体可参考官方文档。
得到的效果是虽然过程很简单,但是很好用
同样的道理可用来求差集。
原文地址: https://blog.csdn.net/LaoChengZier/article/details/80459678