前堤条件:对于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>
取交集
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>
取并集
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>
python pandas取交集、并集、差集