pandas篩選出表中滿足另一個表所有條件的資料
阿新 • • 發佈:2018-12-21
今天記錄一下pandas篩選出一個表中滿足另一個表中所有條件的資料。例如:
list1 結構: 名字,ID,顏色,數量,型別。list1 = [['a',1,255,100,'03'],['a',2,481,50,'06'],['a',47,255,500,'03'],['b',3,1,50,'11']]
list2結構:名字,型別,顏色。list2 = [['a','03',255],['a','06',481]]
如何在list1中找出所有與list2中匹配的元素?要得到下面的結果:list = [['a',1,255,100,'03'],['a',2,481,50,'06'],['a',47,255,500,'03']]。
首先將兩個list轉化為dataframe.
list1 = [['a',1,255,100,'03'],['a',2,481,50,'06'],['a',47,255,500,'03'],['b',3,1,50,'11']]
df1=pd.DataFrame(list1,columns=["名字","ID","顏色","數量","型別"])
list2 = [['a','03',255],['a','06',481]]
df2=pd.DataFrame(list2,columns=["名字","型別","顏色"])
資料結構如下:
然後利用pandas.merge函式將其進行內連線。 這個函式的語法是:
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)。這函式連線方式和sql的連線類似,由引數how來控制。
最後的程式碼如下:
import pandas as pd list1 = [['a',1,255,100,'03'],['a',2,481,50,'06'],['a',47,255,500,'03'],['b',3,1,50,'11']] df1=pd.DataFrame(list1,columns=["名字","ID","顏色","數量","型別"]) list2 = [['a','03',255],['a','06',481]] df2=pd.DataFrame(list2,columns=["名字","型別","顏色"]) df=pd.merge(df1,df2,how='inner',on=["名字","型別","顏色"],right_index=True) df.sort_index(inplace=True) print(df)
返回結果按照左表的順序輸出: