pandas 如何根据值列表选择熊猫中的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35244253/
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-09-14 00:38:45  来源:igfitidea点击:

How to select rows in pandas based on list of values

pythonpandas

提问by Valentin

I'm trying to find out a way how I can select rows in pandas dataframe based that some values will be in my list. For example

我试图找出一种方法,如何根据某些值将在我的列表中来选择 Pandas 数据框中的行。例如

df = pd.DataFrame(np.arange(6).reshape(3,2), columns=['A','B'])
   A  B
0  0  1
1  2  3
2  4  5

I know that I can select certain row, e.g.

我知道我可以选择某些行,例如

df[df.A==0]

will select me row with A=0. What I want is to select multiple rows whose values will be in my list, e.g. A in [0,2]. I tried

将选择 A=0 的行。我想要的是选择其值将在我的列表中的多行,例如 [0,2] 中的 A。我试过

df[df.A in [0,2]]
df[list(df.A)==[0,2]]

but nothing works. In R language I can provide %in% operator. In python syntax we can use A in [0,2], etc. How I can select subset of rows in pandas in this case? Thanks, Valentin.

但没有任何效果。在 R 语言中,我可以提供 %in% 运算符。在 python 语法中,我们可以在 [0,2] 等中使用 A。在这种情况下,我如何在 Pandas 中选择行的子集?谢谢,瓦伦丁。

回答by Brian Huey

pd.isin() will select multiple values:

pd.isin() 将选择多个值:

>>> df[df.A.isin([0,2])]
   A  B
0  0  1
1  2  3

回答by Jeff Ellen

if you don't like that syntax, you can use also use query(introduced in pandas 0.13 which is from 2014):

如果您不喜欢这种语法,也可以使用 use查询(在 2014 年的 pandas 0.13 中引入):

>>> df.query('A in [0,2]')
   A  B
0  0  1
1  2  3