我有一个熊猫数据框架,列名为“内容”,包含文本。我想从本专栏中的每一篇文章中删除一些单词。我想用空字符串替换每个字符串,但是当我打印函数的结果时,我看到单词没有被删除。我的代码如下:
def replace_words(t):
words = ['Livre', 'Chapitre', 'Titre', 'Chapter', 'Article' ]
for i in t:
if i in words:
t.replace (i, '')
else:
continue
print(t)
st = 'this is Livre and Chapitre and Titre and Chapter and Article'
replace_words(st)
理想结果的一个例子是:“这是和”
在下面的代码中,我想将上面的函数应用于列“content”中的每个文本:
df['content'].apply(lambda x: replace_words(x))
有人能帮我创建一个函数,删除我需要的所有单词,然后将这个函数应用到df列中的所有文本中吗?
发布于 2022-10-24 12:00:28
两个问题:
如果使用word.
i
都是一个字母,而不是一个for i in t:
不工作的用这个:
def replace_words(t):
words = ['Livre', 'Chapitre', 'Titre', 'Chapter', 'Article' ]
for i in t.split(' '):
# print(i) # remove to see problem 1
if i in words:
t= t.replace (i, '')
else:
continue
# print(t)
return t
编辑:您可以直接调用df['col'].apply(replace_words)
。
https://stackoverflow.com/questions/74180734
复制相似问题