我有两个专栏在一个相框:害虫和FieldComment
.如果Pests的值被列出为"无",那么我想搜索FieldComment
列中的特定单词并覆盖Pests列中的内容.如果在FieldComment
列中找不到任何单词,则Pests列可以保持为"无".
示例:
pests_list = ['Spiders', 'Rodents', 'Ants', 'Honey Bees']
Pests | FieldComment |
---|---|
Spiders | Performed service. |
None | Performed service for reported rodents. |
以上内容最好变成这样:
Pests | FieldComment |
---|---|
Spiders | Performed service. |
Rodents | Performed service for reported rodents. |
这是我迄今为止try 过的,但我不能完全得到它:
for w in df['FieldComment'].str.split():
for p in pests_list:
if w.str.lower() == p.str.lower():
df['Pests'] = p
我也试过:
df.loc[df['Pests'] == 'None', "Pests"] = *[pest for pest in pest_list if pest in df['FieldComment']]
最后,
df.loc[df['Pests'] == 'None', "Pests"] = df.loc[df['Pests'] == 'None', "Pests"].apply(lambda x: pest for pest in pest_list if pest in df['FieldComment'] else 'None')