【发布时间】:2013-02-25 20:07:16
【问题描述】:
我想在其中一列上使用正则表达式干净地过滤数据框。
举一个人为的例子:
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 []
这不是非常有用。然而,这会给我我的布尔索引:
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
这让我人为地将一个组放入正则表达式中,似乎可能不是干净的方法。有没有更好的方法来做到这一点?
【问题讨论】:
-
如果你不喜欢正则表达式,
foo[foo.b.str.startswith("f")]可以工作。 -
恕我直言,我认为
foo[foo.b.str.match('(f.*)').str.len() > 0]是一个相当不错的解决方案!比startswith更可定制和更有用,因为它包含了正则表达式的多功能性。 -
这可能有点晚,但在新版本的 pandas 中,问题已得到解决。
foo[foo.b.str.match('f.*')]行适用于我的 pandas 0.24.2。