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

对于非一个单元格而是整个列,大熊猫按多个“包含”筛选

  •  4
  • jason  · 技术社区  · 7 年前

    我有很多数据帧,我想找到同时包含我指定的两个词的数据帧。例如,我想查找包含单词的所有数据帧 hello world . A&B有资格,C没有资格。

    我试过了: df[(df[column].str.contains('hello')) & (df[column].str.contains('world'))] 只接B和 df[(df[column].str.contains('hello')) | (df[column].str.contains('world'))] 这三个都有。

    我需要只选A&B的东西

    A=

        Name    Data   
    0   Mike    hello    
    1   Mike    world    
    2   Mike    hello   
    3   Fred    world
    4   Fred    hello
    5   Ted     world
    

    B=

        Name    Data   
    0   Mike    helloworld
    1   Mike    world    
    2   Mike    hello   
    3   Fred    world
    4   Fred    hello
    5   Ted     world
    

    C=

        Name    Data   
    0   Mike    hello
    1   Mike    hello    
    2   Mike    hello   
    3   Fred    hello
    4   Fred    hello
    5   Ted     hello
    
    3 回复  |  直到 7 年前
        1
  •  5
  •   ALollz    7 年前

    如果需要一个bool值 'hello' 在任何地方都能找到 'world' 在一列中的任意位置找到:

    df.Data.str.contains('hello').any() & df.Data.str.contains('world').any()
    

    如果你有一个单词列表,需要检查整个 DataFrame 尝试:

    import numpy as np
    
    lst = ['hello', 'world']
    np.logical_and.reduce([any(word in x for x in df.values.ravel()) for word in lst])
    

    样本数据

    print(df)
       Name   Data   Data2
    0  Mike  hello  orange
    1  Mike  world  banana
    2  Mike  hello  banana
    3  Fred  world  apples
    4  Fred  hello   mango
    5   Ted  world    pear
    
    lst = ['apple', 'hello', 'world']
    np.logical_and.reduce([any(word in x for x in df.values.ravel()) for word in lst])
    #True
    
    lst = ['apple', 'hello', 'world', 'bear']
    np.logical_and.reduce([any(word in x for x in df.values.ravel()) for word in lst])
    # False
    
        2
  •  2
  •   BENY    7 年前

    使用

    import re 
    
    bool(re.search(r'^(?=.*hello)(?=.*world)', df.sum().sum())
    Out[461]: True
    
        3
  •  1
  •   Vaishali    7 年前

    如果hello和world在您的数据中是独立的字符串,df.eq()应该完成这项工作,而不需要str.contains。它不是字符串方法,适用于整个数据帧。

    (((df == 'hello').any()) & ((df == 'world').any())).any()
    
    True