2017-08-08 71 views
1

假設我有使用pandas.dataframe像這樣的列:Python的大熊貓:刪除行不是從數據幀匹配多個條件

index fruits origin  attribute 
1  apple  USA   tasty 
2  apple  France  yummy 
3  apple  USA   juicy 
4  apple  England  juicy 
5  apple  Japan  normal 
6  banana Canada  nice 
7  banana Italy  good 
..... 

我想選擇yummy apple from France(2)和刪除表不匹配​​類似如下:

index fruits origin  attribute 
1  apple  France  yummy 
2  banana Canada  nice 
3  banana Italy  good 
..... 

我認爲以下應該工作。但事實並非如此:

df.drop(df[(df.fruits == "apple") & (df.origin != "France") | (df.fruits == "apple") & (df.attribute != "yummy")].index) 

然後我嘗試這也不起作用的情況如下:

df = df[~df[(df.fruits == "apple") & (df.origin != "France") & (df.attribute != "yummy")] 

任何幫助,小夥子?

+0

@Kev在閆感謝讓我的問題更具可讀性! – Bossam

+0

您可以在PC上使用快捷鍵CTL + k或在Mac上使用CMD + k快速鍵快速格式化代碼段。 –

回答

3

如果選擇通過匹配條件:

df[(df.fruits != 'apple') | ((df.fruits == 'apple') & (df.origin == 'France') & (df.attribute == 'yummy'))] 

#index fruits origin attribute 
#1 2 apple France  yummy 
#5 6 banana Canada  nice 
#6 7 banana Italy  good 

如果不匹配條件刪除:什麼需要被刪除的行,其中fruits是蘋果,而是origin不匹配Franceattribute沒有按」牛逼比賽yummy

df[~((df.fruits == 'apple') & ((df.origin != 'France') | (df.attribute != 'yummy')))] 

# index fruits origin attribute 
#1 2 apple France  yummy 
#5 6 banana Canada  nice 
#6 7 banana Italy  good 
+1

只有秒... – Alexander

1
df.query(
    'fruits == "apple" & origin == "France" & attribute == "yummy"' 
).append(df.query('fruits != "apple"')) 

     fruits origin attribute 
index       
2  apple France  yummy 
6  banana Canada  nice 
7  banana Italy  good 
相關問題