代码之家  ›  专栏  ›  技术社区  ›  Olga

在与列表匹配的系列中搜索元素

  •  0
  • Olga  · 技术社区  · 7 年前

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

    举一个人为的例子:

    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
    

    这让我人为地把一组人加入正则表达式,似乎这不是一个干净的方法。有更好的方法吗?

    0 回复  |  直到 10 年前
        1
  •  233
  •   Dylan Pierce    7 年前

    使用 contains

    In [10]: df.b.str.contains('^f')
    Out[10]: 
    0    False
    1     True
    2     True
    3    False
    Name: b, dtype: bool
    
        2
  •  36
  •   Erkan Şirin    7 年前

    Series.str.startswith() . 你应该试试 foo[foo.b.str.startswith('f')] .

    结果:

        a   b
    1   2   foo
    2   3   fat
    

    我想你期望的是什么。

    或者,您可以将contains与regex一起使用。例如:

    foo[foo.b.str.contains('oo', regex= True, na=False)]
    

    结果:

        a   b
    1   2   foo
    

    na=False 是为了防止在存在nan、null等值时出错

        3
  •  22
  •   ankostis    6 年前

    Series.str.match . 这个 docs 解释两者之间的区别 match , fullmatch contains .

    na=False 争论(或 True 如果要在结果中包含NAN)。

        4
  •  20
  •   m0nhawk Pasqui    10 年前

    使用dataframe进行多列搜索:

    frame[frame.filename.str.match('*.'+MetaData+'.*') & frame.file_path.str.match('C:\test\test.txt')]
    
        5
  •  15
  •   Henry Ecker Super Kai - Kazuya Ito    4 年前

    the great answer 通过 user3136169 ,下面是一个示例,说明如何删除非类型值。

    def regex_filter(val):
        if val:
            mo = re.search(regex,val)
            if mo:
                return True
            else:
                return False
        else:
            return False
    
    df_filtered = df[df['col'].apply(regex_filter)]
    

    您还可以将正则表达式添加为参数:

    def regex_filter(val,myregex):
        ...
    
    df_filtered = df[df['col'].apply(res_regex_filter,regex=myregex)]
    
        6
  •  11
  •   Jean-François Corbett    8 年前

    编写一个布尔函数,检查正则表达式并对列使用apply

    foo[foo['b'].apply(regex_function)]
    
        7
  •  1
  •   BENY    7 年前

    str

    foo[foo.b.str[0]=='f']
    Out[18]: 
       a    b
    1  2  foo
    2  3  fat