我有两个专栏在一个相框:害虫和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')

推荐答案

  1. 将害虫list转换为set.
  2. FieldComment中的单词创建set.
  3. 得到两个set的交集,并填充列Pests为空.
pests_set = set([p.lower() for p in pests_list])

df.loc[df["Pests"].isna(), "Pests"] = df["FieldComment"].apply(
    lambda x: ", ".join(
        set(x.strip(".").lower().split()).intersection(pests_set)
    ).capitalize()
)
     Pests                             FieldComment
0  Spiders                       Performed service.
1  Rodents  Performed service for reported rodents.

如果FieldComment列中有多个害虫名称,则此解决方案将把害虫名称与,连接.对于这一个框架:

     Pests                                FieldComment
0  Spiders                          Performed service.
1     None  Performed service for rodents and spiders.

结果将是:

              Pests                                FieldComment
0           Spiders                          Performed service.
1  Spiders, rodents  Performed service for rodents and spiders.

请注意,如果rabrame有一个str 'None',而不是None关键字,您必须稍微修改上面的代码,将df["Pests"].isna()替换为df["Pests"] == 'None'.

Python相关问答推荐

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

使用SciPy进行曲线匹配未能给出正确的匹配

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

Pandas - groupby字符串字段并按时间范围 Select

更改键盘按钮进入'

OR—Tools中CP—SAT求解器的IntVar设置值

从spaCy的句子中提取日期

递归访问嵌套字典中的元素值

当递归函数的返回值未绑定到变量时,非局部变量不更新:

在Python 3中,如何让客户端打开一个套接字到服务器,发送一行JSON编码的数据,读回一行JSON编码的数据,然后继续?

在Python中使用if else或使用regex将二进制数据如111转换为001""

使用Openpyxl从Excel中的折线图更改图表样式

通过追加列表以极向聚合

使用SeleniumBase保存和加载Cookie时出现问题

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

仅取消堆叠最后三列

如何从一个维基页面中抓取和存储多个表格?

Python:使用asyncio.StreamReader.readline()读取长行