如何通过正则表达式过滤 pandas 中的行 [英] How to filter rows in pandas by regex
本文介绍了如何通过正则表达式过滤 pandas 中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在其中一列上使用regex干净地过滤数据框.
I would like to cleanly filter a dataframe using regex on one of the columns.
举一个人为的例子:
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
开头的行.首先去:
I want to filter the rows to those that start with f
using a regex. First go:
In [213]: foo.b.str.match('f.*')
Out[213]:
0 []
1 ()
2 ()
3 []
这不是太有用了.但是,这将使我得到我的布尔值索引:
That's not too terribly useful. However this will get me my boolean index:
In [226]: foo.b.str.match('(f.*)').str.len() > 0
Out[226]:
0 False
1 True
2 True
3 False
Name: b
然后我可以通过以下方式进行限制:
So I could then do my restriction by:
In [229]: foo[foo.b.str.match('(f.*)').str.len() > 0]
Out[229]:
a b
1 2 foo
2 3 fat
虽然这使我人为地将一个组放入正则表达式中,但似乎不是一种干净的方法.有更好的方法吗?
That makes me artificially put a group into the regex though, and seems like maybe not the clean way to go. Is there a better way to do this?
推荐答案
使用 查看全文