2017-06-08 63 views
0
Title URL Price Address Rental_Type 
0 House URL $600 Auburn Apartment 
1 House URL $600 Auburn Apartment 
2 House URL $900 NY  Apartment 
3 Room! URL $1018 NaN  Office 
4 Room! URL $910 NaN  Office 

我試圖刪除Title下的重複項。但我只想刪除有Rental_Type == 'Office'的行。我也有第二個約束。我想刪除與Rental_Type == 'Apartment'行,但我想保留在這種情況下的第一個重複。所以在這種情況下,第3行和第4行將下降,然後只有第1行從第0/1行開始。熊貓:刪除重複項,在另一列中有約束條件

回答

0

我會逐步建立起來,以構建您希望放棄的事件列表。

offices = df['Rental_Type'] == 'Office' 
apts = df['Rental_Type'] == 'Apartment' 

dup_offices = df[offices].duplicated('Title', keep=False) 
dup_apts = df[apts].duplicated('Title', keep='first') 

to_drop = pd.Index(dup_apts[dup_apts].index.tolist() + \ 
        dup_offices[dup_offices].index.tolist()) 

df = df.drop(to_drop) 
0

您可以用這種方式與您的約束條件刪除重複項:

#drop all duplicate with Rental_Type=='Office' 
    df1 = df[(df.Rental_Type=='Office')].drop_duplicates(['Title'], keep=False) 

    #Capture the duplicate row with Rental_Type=='Apartment' 
    df2 = df[(df.Rental_Type=='Apartment')].duplicated(['Title'], keep = 'last') 
    df3=df[(df.Rental_Type=='Apartment')][df2.values][1:] 

    #Put them together 
    df_final = pd.concat([df1,df3]) 


In [1]: df_final 
Out[1]: 
    Title URL Price Address Rental_Type 
1 House URL 600  Auburn Apartment