将列表中每行单词替换为Pandas

inkz8wg9  于 2023-01-07  发布在  其他
关注(0)|答案(3)|浏览(156)

我有一个单词表:

word = ['dog', 'cat', 'fish']

这个 Dataframe :

dfa = pd.DataFrame({'a': ['big dog', 'good food', 'dog and cat', 'little fish', 'intense light', 'nice cat']})

当单词列表中的文本出现在dataframe列中时,我想替换它。我已尝试执行此操作:

for row in dfa['a']:
   for w in word:
       if w in row:
           dfa['a'] = dfa['a'].replace(w, "animal")

我没发现任何错误。但它就是不工作
这是我最后想要的

a
big animal
good food
animal and animal
little animal
intense light
nice animal

我怎样才能做到这一点?

tag5nh1u

tag5nh1u1#

你可以只遍历要替换的单词,而不是每行一个单词。注意regex参数,它允许查找和替换子字符串。你可以在pandas.DataFrame.replacehere的文档中找到更多信息。

import pandas as pd

word = ['dog', 'cat', 'fish']

dfa = pd.DataFrame({'a': ['big dog', 'good food', 'dog and cat', 'little fish', 'intense light', 'nice cat']})

for w in word:
    dfa = dfa.replace(w, "animal", regex=True)

print(dfa)

此输出

a
0         big animal
1          good food
2  animal and animal
3      little animal
4      intense light
5        nice animal
bpsygsoo

bpsygsoo2#

import pandas as pd

dfa = pd.DataFrame({'a': ['big dog', 'good food', 'dog and cat', 'little fish', 'intense light', 'nice cat']})
word = ['dog', 'cat', 'fish']

out = dfa["a"].str.replace(f"({'|'.join(word)})", "animal", regex=True)
0           big animal
1            good food
2    animal and animal
3        little animal
4        intense light
5          nice animal
Name: a, dtype: object
f2uvfpb9

f2uvfpb93#

用途

dfa['a'] = dfa['a'].str.replace(w, "animal")

相关问题