检查列表中的单词并删除pandas dataframe列

时间:2017-08-01 21:18:31

标签: python regex python-2.7 pandas replace

我有一个如下列表,

remove_words = ['abc', 'deff', 'pls']

以下是我使用列名'字符串'

的数据框
     data['string']

0    abc stack overflow
1    abc123
2    deff comedy
3    definitely
4    pls lkjh
5    pls1234

我想检查pandas dataframe列中remove_words列表中的单词,并删除pandas数据帧中的这些单词。我想检查单独出现的单词,而不是用其他单词出现。

例如,如果有' abc'在pandas df专栏中,将其替换为''但如果它与abc123一起发生,我们需要保持原样。这里的输出应该是,

     data['string']

0    stack overflow
1    abc123
2    comedy
3    definitely
4    lkjh
5    pls1234

在我的实际数据中,我在remove_words列表中有2000个单词,在pandas数据框中有50亿个记录。所以我正在寻找最有效的方法。

我在python中尝试过很少的东西,没有太大的成功。有人可以帮我这么做吗?任何想法都会有所帮助。

由于

2 个答案:

答案 0 :(得分:8)

试试这个:

In [98]: pat = r'\b(?:{})\b'.format('|'.join(remove_words))

In [99]: pat
Out[99]: '\\b(?:abc|def|pls)\\b'

In [100]: df['new'] = df['string'].str.replace(pat, '')

In [101]: df
Out[101]:
               string              new
0  abc stack overflow   stack overflow
1              abc123           abc123
2          def comedy           comedy
3          definitely       definitely
4            pls lkjh             lkjh
5             pls1234          pls1234

答案 1 :(得分:3)

完全采用@ MaxU的模式!

我们可以通过将regex参数设置为True并传递字典词典来指定模式以及每列的替换内容,从而使用pd.DataFrame.replace

pat = '|'.join([r'\b{}\b'.format(w) for w in remove_words])

df.assign(new=df.replace(dict(string={pat: ''}), regex=True))

               string              new
0  abc stack overflow   stack overflow
1              abc123           abc123
2          def comedy           comedy
3          definitely       definitely
4            pls lkjh             lkjh
5             pls1234          pls1234
相关问题