【问题标题】:Need to select values from a column using a list of strings using pandas.str() [duplicate]需要使用 pandas.str() 使用字符串列表从列中选择值 [重复]
【发布时间】:2019-10-13 18:39:42
【问题描述】:

需要从字符串列表中搜索字符串列值。搜索列表中的字符串只是列中值的子字符串

df = pd.DataFrame(data={'text':['abc def', 'def ghi', 'poi opo', 'aswwf', 'abcs  sd'], 'id':[1, 2, 3, 4, 5]})

Out [1]:
    text     id
0   abc def  1
1   def ghi  2
2   poi opo  3
3   aswwf    4
4   abcs sd  5

search = ['abc', 'poi']

必填:


Out [2]:
    text     id
0   abc def  1
1   poi opo  3
2   abcs sd  5

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用Series.str.containsboolean indexing - 列表的所有值都由| 加入正则表达式OR

    pat = '|'.join(search)
    df1 = df[df['text'].str.contains(pat)]
    print (df1)
           text  id
    0   abc def   1
    2   poi opo   3
    4  abcs  sd   5
    

    【讨论】:

      【解决方案2】:

      @jezrael'answer 很棒,只要要搜索的模式不包含像 | 这样的特殊字符。但是您可以一次处理每个元素并在最后执行全局 。如果要搜索包含特殊字符的字符串,可以使用:

      df[pd.concat([df.text.str.contains(i, regex=False) for i in search], axis=1).any(axis=1)]
      

      它按预期给出:

             text  id
      0   abc def   1
      2   poi opo   3
      4  abcs  sd   5
      

      【讨论】:

        猜你喜欢
        • 2020-11-12
        • 2016-06-08
        • 2020-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多