2017-08-21 72 views
1

這應該是非常容易,但我不能讓它工作。python pandas loc - 過濾器的值列表

我想過濾我的數據集的兩個值。

#this works, when I filter for one value 
df.loc[df['channel'] == 'sale'] 

#if I have to filter, two separate columns, I can do this 
df.loc[(df['channel'] == 'sale')&(df['type]=='A')] 

#but what if I want to filter one column by more than one value? 
df.loc[df['channel'] == ('sale','fullprice')] 

這是否必須是OR語句?我可以在SQL中使用類似的東西嗎?

+3

'df.loc [df ['channel']。isin(['sale','fullprice'])]' – MaxU

+0

非常感謝! – jeangelj

回答

3

存在df.isin(values)測試方法 DataFrame中的每個元素是否包含在值中。 所以,@MaxU在評論中寫道,您可以使用

df.loc[df['channel'].isin(['sale','fullprice'])] 

由多個值過濾一列。

+1

''df.loc [df ['channel']。apply(lambda x:x in ['sale','fullprice'])]'也可以。它不如使用'df.isin'簡潔,但可以修改,以檢查任何摺疊條件,這取決於只有一列。 – tipanverella

+1

是的,絕對。 – taras

+0

很棒 - 謝謝你的選擇,超好玩! – jeangelj