Python【Pandas】取交集、并集、差集

前堤条件:对于colums都相同的dataframe做过滤的时候

创建2个结构(列名)一致的DataFrame,df1和df2有1条重合的数据

import pandas as pd

df1=pd.DataFrame([['a',10,'男'],['b',11,'女']],columns=['name','age','gender'])
df2=pd.DataFrame([['a',10,'男']],columns=['name','age','gender'])
df1
<style scoped=""> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
name age gender
0 a 10
1 b 11
df2
<style scoped=""> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
name age gender
0 a 10

取交集

pd.merge(df1,df2,on=['name','age','gender'])
<style scoped=""> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
name age gender
0 a 10

取并集

pd.merge(df1,df2,on=['name','age','gender'],how='outer')
<style scoped=""> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
name age gender
0 a 10
1 b 11

取差集

df1=df1.append(df2)
df1=df1.drop_duplicates(subset=['name','age','gender'],keep=False)
df1
<style scoped=""> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
name age gender
1 b 11

python pandas取交集、并集、差集

上一篇:el-table表格拖动排序


下一篇:JSON格式化 动态生成表格 表格转置 行列转换 Excel导出