【问题标题】:Search multi-string in pandas column在 pandas 列中搜索多字符串
【发布时间】:2021-09-05 21:40:33
【问题描述】:

我有一个看起来像这样的熊猫数据框:

       col1   col2
   0   1      A
   1   10     A, B
   2   20     B
   3   5      C
   4   70     A, B, C

现在我想在给定条件下搜索 col2 并相应地选择行。例如:

search_pattern = ["A"] -> Select all rows where A is present [rows 0, 1, 4]
search_pattern = ["A", "B"] -> Select all rows where A is present and B is present [rows 1, 4]
search_pattern = ["B"] -> Select all rows where B is present [rows 1, 2, 4]

    

【问题讨论】:

    标签: python pandas string numpy


    【解决方案1】:

    您可以在Series.map 中拆分值并与issubset 的集合进行比较:

    search_pattern1 = ["A"] 
    search_pattern2 = ["A", "B"] 
    search_pattern3 = ["B"] 
    
    pats = [search_pattern1, search_pattern2, search_pattern3]
    
    for pat in pats:
        df1 = df[df['col2'].str.split(', ').map(set(pat).issubset)]
        print (df1)
    

       col1     col2
    0     1        A
    1    10     A, B
    4    70  A, B, C
       col1     col2
    1    10     A, B
    4    70  A, B, C
       col1     col2
    1    10     A, B
    2    20        B
    4    70  A, B, C
    

    【讨论】:

      【解决方案2】:

      如果您的 DataFrame 存储在变量 df 中,您可以这样做

      df[df.col2.apply(
        lambda c: all(el in c.replace(' ', '').split(',') for el in search_pattern)
      )]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-09
        • 2022-01-03
        • 2022-01-03
        • 2016-11-02
        • 2015-05-20
        • 2022-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多