【问题标题】:Pandas str.contains, containing all the given charactersPandas str.contains,包含所有给定的字符
【发布时间】:2015-03-24 20:47:15
【问题描述】:

是否可以使用 str.contain 搜索包含所有给定字符的字符串?

这行得通:

df["col1"].str.contains("A")

如果我想找到至少一个给定的字符,这个也可以:

df["col1"].str.contains("A|B")

但是,如果我想查找包含所有给定字符的字符串,这是行不通的

df["col1"].str.contains("A&B")

结果全是假的。

有什么建议吗? 谢谢!

【问题讨论】:

    标签: python pandas dataframe contains


    【解决方案1】:

    另一种方法:

    df['col1'].apply(set('AB').issubset)
    

    还有一些示例时间:

    import pandas as pd
    import numpy as np
    
    strings = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', 'CABA', 'dog', 'cat'])
    %timeit strings.apply(set('AB').issubset)
    # 10000 loops, best of 3: 102 µs per loop
    %timeit strings.str.contains('A.*B|B.*A')
    # 10000 loops, best of 3: 149 µs per loop
    %timeit strings.str.contains('A') & strings.str.contains('B')
    # 1000 loops, best of 3: 712 µs per loop
    

    【讨论】:

    • 干得好!在这里工作的乐趣之一是学习其他(更好的)解决问题的方法。
    【解决方案2】:

    要么

    df['col1'].str.contains('A.*B|B.*A')
    

    df['col1'].str.contains('A') & df['col1'].str.contains('B')
    

    示例:

    >>> df
          col1
    0  wAxyzBw
    1  wBxyzAw
    2    wAxyz
    3    wBxyz
    >>> df['col1'].str.contains('A.*B|B.*A')
    0     True
    1     True
    2    False
    3    False
    Name: col1, dtype: bool
    >>> df['col1'].str.contains('A') & df['col1'].str.contains('B')
    0     True
    1     True
    2    False
    3    False
    Name: col1, dtype: bool
    

    【讨论】:

      【解决方案3】:

      如果您正在寻找大量(或最初未知的)字符集,那么执行此操作的更通用的方法是

      DataFrame({key: df.col1.str.contains(key) for key in 'AB'}).all(axis=1)
      

      可能有更好的方法来做到这一点(通常在 pandas 中:),但它给了我与 @benzad.nouri 在 5 毫米行 DF 上的答案相当的性能。

      【讨论】:

        猜你喜欢
        • 2013-05-13
        • 2013-08-19
        • 1970-01-01
        • 2021-02-10
        • 2021-12-16
        • 2011-01-28
        • 2019-02-06
        • 1970-01-01
        相关资源
        最近更新 更多