根据精确的字符串匹配过滤 Pandas 数据帧

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

Filter Pandas Data Frame based on exact string match

pythonstringpandas

提问by Abhijith N

I want to filter a pandas data frame based on exact match of a string.

我想根据字符串的精确匹配过滤Pandas数据框。

I have a data frame as below

我有一个如下的数据框

df1 = pd.DataFrame({'vals': [1, 2, 3, 4,5], 'ids': [u'aball', u'bball', u'cnut', u'fball','aballl']})    

I want to filter all the rows except the row that has 'aball'.As you can see I have one more entry with ids == 'aballl'. I want that filterd out. Hence the below code does not work:

我想过滤除具有“aball”的行之外的所有行。如您所见,我还有一个 ids == 'aball' 的条目。我想过滤掉。因此下面的代码不起作用:

df1[df1['ids'].str.contains("aball")]    

even str.match does not work

即使 str.match 也不起作用

df1[df1['ids'].str.match("aball")] 

Any help would be greatly appreciated.

任何帮助将不胜感激。

回答by IanS

Keeping it simple, this should work:

保持简单,这应该有效:

df1[df1['ids'] == "aball"] 

回答by Nick M

You can try this:

你可以试试这个:

df1[~(df1['ids'] == "aball")] 

Essentially it will find all entries matching "aball" and then negate it.

本质上它会找到所有匹配“aball”的条目,然后否定它。