python - 如何通过正则表达式过滤 Pandas 中的行

标签 python regex pandas

我想在其中一列上使用正则表达式干净地过滤数据框。

举一个人为的例子:

In [210]: foo = pd.DataFrame({'a' : [1,2,3,4], 'b' : ['hi', 'foo', 'fat', 'cat']})
In [211]: foo
Out[211]: 
   a    b
0  1   hi
1  2  foo
2  3  fat
3  4  cat

我想使用正则表达式将行过滤为以 f 开头的行。先去吧:

In [213]: foo.b.str.match('f.*')
Out[213]: 
0    []
1    ()
2    ()
3    []

这不是非常有用。然而,这会给我我的 bool 索引:

In [226]: foo.b.str.match('(f.*)').str.len() > 0
Out[226]: 
0    False
1     True
2     True
3    False
Name: b

所以我可以通过以下方式进行限制:

In [229]: foo[foo.b.str.match('(f.*)').str.len() > 0]
Out[229]: 
   a    b
1  2  foo
2  3  fat

这让我人为地将一个组放入正则表达式中,似乎可能不是干净的方法。有没有更好的方法来做到这一点?

最佳答案

使用 contains而是:

In [10]: df.b.str.contains('^f')
Out[10]: 
0    False
1     True
2     True
3    False
Name: b, dtype: bool

关于python - 如何通过正则表达式过滤 Pandas 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15325182/

相关文章:

python - numpy nanmean 错误

python - Pygame + python : 1 part of code has pygame. 等待其余代码运行

python - 使用 Python 在 Appengine 中解析 xml 的最佳方法

javascript - 如何使用匹配的正则表达式获取多行文本的最后一行?

pandas - HoloViews:为 pandas 数据框中的每一列创建箱线图

python - 如何获得数据帧之间的总时间重叠量?

c++ - 正则表达式算法

java - 如何捕获用户在文本中给出的 URL

Python:替换 DataFrame 中的 "{}"

python - matplotlib boxplot xticks 向 y 轴移动