简体   繁体   English

熊猫数据帧过滤器正则表达式

[英]pandas DataFrame filter regex

I don't understand pandas DataFrame filter .我不明白pandas DataFrame filter

Setup设置

import pandas as pd

df = pd.DataFrame(
    [
        ['Hello', 'World'],
        ['Just', 'Wanted'],
        ['To', 'Say'],
        ['I\'m', 'Tired']
    ]
)

Problem问题

df.filter([0], regex=r'(Hel|Just)', axis=0)

I'd expect the [0] to specify the 1st column as the one to look at and axis=0 to specify filtering rows.我希望[0]将第一列指定为要查看的列,并且axis=0指定过滤行。 What I get is this:我得到的是这样的:

       0      1
0  Hello  World

I was expecting我期待

       0       1
0  Hello   World
1   Just  Wanted

Question问题

  • What would have gotten me what I expected?什么会让我达到我的预期?

Per the docs ,根据文档

Arguments are mutually exclusive, but this is not checked for参数是互斥的,但这不会被检查

So, it appears, the first optional argument, items=[0] trumps the third optional argument, regex=r'(Hel|Just)' .因此,看起来,第一个可选参数items=[0]胜过第三个可选参数regex=r'(Hel|Just)'

In [194]: df.filter([0], regex=r'(Hel|Just)', axis=0)
Out[194]: 
       0      1
0  Hello  World

is equivalent to相当于

In [201]: df.filter([0], axis=0)
Out[201]: 
       0      1
0  Hello  World

which is merely selecting the row(s) with index values in [0] along the 0-axis.这只是沿着 0 轴选择索引值在[0]行。


To get the desired result, you could use str.contains to create a boolean mask, and use df.loc to select rows:要获得所需的结果,您可以使用str.contains创建一个布尔掩码,并使用df.loc来选择行:

In [210]: df.loc[df.iloc[:,0].str.contains(r'(Hel|Just)')]
Out[210]: 
       0       1
0  Hello   World
1   Just  Wanted

这应该有效:

df[df[0].str.contains('(Hel|Just)', regex=True)]

这是一个链接方法:

df.loc[lambda x: x['column_name'].str.contains(regex_patern, regex = True)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM