代码之家  ›  专栏  ›  技术社区  ›  Anakin Skywalker

使用Python过滤数据帧中不包含特定单词的字符串行

  •  0
  • Anakin Skywalker  · 技术社区  · 4 年前

    我有一个带有“文本”列的数据框。

    我想过滤掉除行之外的所有内容 text 列,包含某些字符串。 我的单词表很长。例如,犯罪、税收等。

    这只适用于一个词:

    data_cleaned = data_cleaned.loc[data_cleaned['text'].str.contains('population')].reset_index(drop = True)
    

    如何添加多个单词,不仅有人口,还有犯罪等。

    我看到了答案 like this ,但它对我不起作用。

    UPD。

    我的完整单词列表如下

    key_words = ['population'
                              'migrarion'
                              'crime',
                              'safety',
                              'taxation',
                              'taxes',
                              'weather', 
                              'climate',
                              'opportunities',
                              'employment',
                              'unemployment',
                              'cultural life',
                              'services',
                              'jobs',
                              'economic growth',
                              'economic decline',
                              'pollution',
                              'environment',
                              'health',
                              'insurance',
                              'education',
                              'natural disaster',
                              'retirement']
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   bb1    4 年前

    假设 lst 是以下字符串的列表:

    def selector(s):
        for w in lst:
            if w in s:
                return True
        return False
    
    data_cleaned = data_cleaned.loc[data_cleaned['text'].apply(selector)]