Python-删除所有不在列表中的子字符串

时间:2018-07-09 11:25:10

标签: python string pandas

我想删除df列中所有未在定义列表中出现的子字符串。例如:

mylist = {good, like, bad, hated, terrible, liked}

Current:                                         Desired:
index      content                               index        content                                          
0          a very good idea, I like it           0            good like
1          was the bad thing to do               1            bad
2          I hated it, it was terrible           2            hated terrible
...                                              ...
k          Why do you think she liked it         k            liked

我设法定义了一个函数,该函数使所有单词都不在列表中,但是不知道如何反转该函数来实现我想要的功能:

pat = r'\b(?:{})\b'.format('|'.join(mylist))
df['column1'] = df['column1'].str.contains(pat, '')

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:5)

str.findallstr.join一起使用:

df['column1'] = df['content'].str.findall('(' + pat + ')').str.join(' ')
print (df)
                         content         column1
0    a very good idea, I like it       good like
1        was the bad thing to do             bad
2    I hated it, it was terrible  hated terrible
3  Why do you think she liked it           liked

或通过拆分,过滤和合并列出列表:

df['column1'] = df['content'].apply(lambda x: ' '.join([y for y in x.split() if y in mylist]))
print (df)
                         content         column1
0    a very good idea, I like it       good like
1        was the bad thing to do             bad
2    I hated it, it was terrible  hated terrible
3  Why do you think she liked it           liked