python pandas loc - 过滤值列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45803676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:17:37  来源:igfitidea点击:

python pandas loc - filter for list of values

pythonpandasfilterloc

提问by jeangelj

This should be incredibly easy, but I can't get it to work.

这应该非常容易,但我无法让它工作。

I want to filter my dataset on two or more values.

我想根据两个或多个值过滤我的数据集。

#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')] 

Would this have to be an OR statement? I can do something like in SQL using in?

这是否必须是 OR 语句?我可以在 SQL 中使用 in?

回答by taras

There is a df.isin(values)method wich tests whether each element in the DataFrameis contained in values. So, as @MaxU wrote in the comment, you can use

有一种df.isin(values)方法可以测试 中的每个元素是否DataFrame包含在values. 因此,正如@MaxU 在评论中所写,您可以使用

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

to filter one column by multiple values.

按多个值过滤一列。