从 Pandas Dataframe 中提取在特定列中具有特定值的所有行

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

Extracting all rows from pandas Dataframe that have certain value in a specific column

pythonpandasdataframe

提问by user1083734

I am relatively new to Python/Pandas and am struggling with extracting the correct data from a pd.Dataframe. What I actually have is a Dataframe with 3 columns:

我对 Python/Pandas 比较陌生,正在努力从 pd.Dataframe 中提取正确的数据。我实际拥有的是一个包含 3 列的数据框:

data =

Position Letter Value
1        a      TRUE
2        f      FALSE
3        c      TRUE
4        d      TRUE
5        k      FALSE

What I want to do is put all of the TRUE rows into a new Dataframe so that the answer would be:

我想要做的是将所有 TRUE 行放入一个新的 Dataframe 中,以便答案是:

answer = 

Position Letter Value
1        a      TRUE
3        c      TRUE
4        d      TRUE

I know that you can access a particular column using

我知道您可以使用访问特定列

data['Value']

but how do I extract all of the TRUE rows?

但是如何提取所有 TRUE 行?

Thanks for any help and advice,

感谢您的任何帮助和建议,

Alex

亚历克斯

回答by Andy Hayden

You can test which Values are True:

您可以测试哪些值为 True:

In [11]: data['Value'] == True
Out[11]:
0     True
1    False
2     True
3     True
4    False
Name: Value, dtype: bool

and then use fancy indexing to pull out those rows:

然后使用花哨的索引来提取这些行:

In [12]: data[data['Value'] == True]
Out[12]:
   Position Letter Value
0         1      a  True
2         3      c  True
3         4      d  True

*Note: if the values are actually the strings 'TRUE'and 'FALSE'(they probably shouldn't be!) then use:

*注意:如果值实际上是字符串'TRUE'并且'FALSE'(它们可能不应该是!)然后使用:

data['Value'] == 'TRUE'