代码之家  ›  专栏  ›  技术社区  ›  Claudiu Creanga

使用查询函数返回两个列表相交的行

  •  2
  • Claudiu Creanga  · 技术社区  · 7 年前

    我有这个df:

    pd.DataFrame([[1, "type_1"], [2, "type_2"], [2, "type_1; type_2"], [2, "type_1; type_3"], [2, "type_3"], [2, "type_1; type_2, type_3"]],
                         columns=["a", "b"])
        a   b
    0   1   type_1
    1   2   type_2
    2   2   type_1; type_2
    3   2   type_1; type_3
    4   2   type_3
    5   2   type_1; type_2, type_3
    

    my_list = ["type_1", "type_2"]
    df.query("a == 2 and b in @my_list")
    

    现在这个输出:

        a   b
    1   2   type_2
    

    但我希望输出是这样的,因为我的_列表中至少有一个b值:

        a   b
    0   2   type_2
    1   2   type_1; type_2
    2   2   type_1; type_3
    3   2   type_1; type_2, type_3
    

    . 目前,它们是由两条线分隔的字符串 ; 但我可以把它们转换成列表。但是,我不确定这将如何帮助我筛选至少有一个值的行 column b 在…内 my_list 仅使用.query() (因为否则我将不得不解析查询字符串,它会变得混乱)

    这将是具有列表的等效代码:

    pd.DataFrame([[1, ["type_1"]], [2, ["type_2"]], [2, ["type_1", "type_2"]], [2, ["type_1", "type_3"]], [2, "type_3"], [2, ["type_1", "type_2", "type_3"]]],
                         columns=["a", "b"])
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   BENY    7 年前

    你可以使用 str.split isin any 是完全匹配的,这意味着如果你 type_11 ,使用 伊辛 它会回来的 False

    df[(pd.DataFrame(df.b.str.split(';').tolist()).isin(my_list).any(1))&(df.a==2)]
    Out[88]: 
       a                       b
    1  2                  type_2
    2  2          type_1; type_2
    3  2          type_1; type_3
    5  2  type_1; type_2, type_3
    
        2
  •  3
  •   cs95 abhishek58g    7 年前

    “python”引擎支持。

    df.query("a == 2 and b.str.contains('|'.join(@my_list))", engine='python')
    
       a                       b
    1  2                  type_2
    2  2          type_1; type_2
    3  2          type_1; type_3
    5  2  type_1; type_2, type_3
    

    (旧答案)您的查询可以分为两部分:需要子字符串检查的部分和其他所有部分。

    str.contains DataFrame.eval df .

    m1 = df.eval("a == 2")
    m2 = df['b'].str.contains('|'.join(my_list))
    
    df[m1 & m2]
    
       a                       b
    1  2                  type_2
    2  2          type_1; type_2
    3  2          type_1; type_3
    5  2  type_1; type_2, type_3