【问题标题】:How to filter rows containing specific string values with an AND operator如何使用 AND 运算符过滤包含特定字符串值的行
【发布时间】:2018-04-17 21:58:15
【问题描述】:

我的问题是这个链接中回答得很好的问题的延伸:

我已经在下面发布了答案,当字符串包含单词“ball”时,它们会被过滤掉:

In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
     ids     vals
0  aball     1
1  bball     2
3  fball     4

现在我的问题是:如果我的数据中有很长的句子,并且我想用“ball”和“field”来识别字符串怎么办?这样当只有一个单词出现时,它会丢弃包含单词“ball”或“field”的数据,但保留字符串中同时包含两个单词的数据。

【问题讨论】:

  • 顺便说一句,如果搜索固定字符串(即不是正则表达式),您通常可以使用 df['ids'].str.contains("ball", regex=False) 来提高速度。

标签: python pandas filtering


【解决方案1】:
df[df['ids'].str.contains("ball")]

会变成:

df[df['ids'].str.contains("ball") & df['ids'].str.contains("field")]

如果你喜欢更简洁的代码:

contains_balls = df['ids'].str.contains("ball")
contains_fields = df['ids'].str.contains("field")

filtered_df = df[contains_balls & contains_fields]

【讨论】:

  • 太棒了!你在这里拯救了我的夜晚!
  • 谢谢。你碰巧知道这是记录在哪里吗?
【解决方案2】:

如果你有2个以上,你可以使用这个..(注意速度不如foxyblue的方法)

l = ['ball', 'field']
df.ids.apply(lambda x: all(y in x for y in l))

【讨论】:

  • 作为一个美丽的人,你应该少用单字母变量
  • 虽然答案很明确
  • @GiantsLoveDeathMetal 知道了 :-) ,将继续提高我的代码可读性:-)
【解决方案3】:

您可以使用np.logical_and.reducestr.contains 处理多个单词。

df[np.logical_and.reduce([df['ids'].str.contains(w) for w in ['ball', 'field']])]

In [96]: df
Out[96]:
             ids
0  ball is field
1     ball is wa
2  doll is field

In [97]: df[np.logical_and.reduce([df['ids'].str.contains(w) for w in ['ball', 'field']])]
Out[97]:
             ids
0  ball is field

【讨论】:

    【解决方案4】:

    另一种正则表达式方法:

    In [409]: df
    Out[409]:
                   ids
    0   ball and field
    1  ball, just ball
    2      field alone
    3  field and ball
    
    In [410]: pat = r'(?:ball.*field|field.*ball)'
    
    In [411]: df[df['ids'].str.contains(pat)]
    Out[411]:
                   ids
    0   ball and field
    3  field and ball
    

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 2021-09-08
      • 2022-12-05
      相关资源
      最近更新 更多