1. 程式人生 > >pandas DataFrame 交集並集補集

pandas DataFrame 交集並集補集

1.0 brief 詳細 技術分享 rop utf-8 col pri and

1.場景,對於colums都相同的dataframe做過濾的時候

例如:

df1 = DataFrame([[‘a‘, 10, ‘男‘], 
[‘b‘, 11, ‘男‘],
[‘c‘, 11, ‘女‘],
[‘a‘, 10, ‘女‘],
[‘c‘, 11, ‘男‘]],
columns=[‘name‘, ‘age‘, ‘sex‘])

df2 = DataFrame([[‘a‘, 10, ‘男‘],
[‘b‘, 11, ‘女‘]],
columns=[‘name‘, ‘age‘, ‘sex‘])

取交集:print(pd.merge(df1,df2,on=[‘name‘, ‘age‘, ‘sex‘]))
取並集:print(pd.merge(df1,df2,on=[‘name‘, ‘age‘, ‘sex‘], how=‘outer‘))
取差集(從df1中過濾df1在df2中存在的行):
df1 = df1.append(df2)
df1 = df1.append(df2)
df1 = df1.drop_duplicates(subset=[‘name‘, ‘age‘, ‘sex‘],keep=False)
print(df1)

代碼:
# -*- coding:utf-8 -*-
__version__ = ‘1.0.0.0‘
"""
@brief : 簡介
@details: 詳細信息
@author : zhphuang
@date : 2018-10-29
"""

import pandas as pd
from pandas import *

df1 = DataFrame([[‘a‘, 10, ‘男‘],
[‘b‘, 11, ‘男‘],
[‘c‘, 11, ‘女‘],
[‘a‘, 10, ‘女‘],
[‘c‘, 11, ‘男‘]],
columns=[‘name‘, ‘age‘, ‘sex‘])
print("df1:\n%s\n\n" % df1)
df2 = DataFrame([[‘a‘, 10, ‘男‘],
[‘b‘, 11, ‘女‘]],
columns=[‘name‘, ‘age‘, ‘sex‘])
print("df2:\n%s\n\n" % df2)
# 取交集
print("交集:\n%s\n\n" % pd.merge(df1,df2,on=[‘name‘, ‘age‘, ‘sex‘]))

# 取並集
print("並集:\n%s\n\n" % pd.merge(df1,df2,on=[‘name‘, ‘age‘, ‘sex‘], how=‘outer‘))

# 從df1中過濾df1在df2中存在的行,也就是取補集
df1 = df1.append(df2)
df1 = df1.append(df2)
print("補集(從df1中過濾df1在df2中存在的行):\n%s\n\n" % df1.drop_duplicates(subset=[‘name‘, ‘age‘, ‘sex‘],keep=False))
截圖 
技術分享圖片

 

pandas DataFrame 交集並集補集