我想在其中一列上使用正则表达式干净地过滤数据框。
举一个人为的例子:
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/