如何使用正则表达式删除 python pandas DataFrame 中的行?

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

How to delete rows in python pandas DataFrame using regular expressions?

pythonregexpandas

提问by Alexander

I have a pattern:

我有一个模式:

patternDel = "( \((MoM|QoQ)\))";

And I want to delete all rows in pandas dataframe where column df['Event Name']matches this pattern. Which is the best way to do it? There are more than 100k rows in dataframe.

我想删除 Pandas 数据框中列df['Event Name']匹配此模式的所有行。哪种方法最好?数据帧中有超过 10 万行。

回答by Bob Haffner

str.contains()returns a Series of booleans that we can use to index our frame

str.contains()返回一系列布尔值,我们可以用它来索引我们的框架

patternDel = "( \((MoM|QoQ)\))"
filter = df['Event Name'].str.contains(patternDel)

I tend to keep the things we want as opposed to delete rows. Since filter represents things we want to delete we use ~to get all the rows that don't match and keep them

我倾向于保留我们想要的东西而不是删除行。由于过滤器代表我们想要删除的东西,我们~用来获取所有不匹配的行并保留它们

df = df[~filter]