删除一个单词,除非它是另一个单词的一部分 - python

我想删除花药单词中单词部分以外的特定单词
这是例子

data1 
    name    

    here is a this       
    company 
    there is no food      

data2
    words   count

    is       56
    com     17
    no      22

我写了这个功能,但问题是如果另一个词的一部分,它会删除一个词


def drop(y):
    for x in data2.words.values:
        y['name']= y['name'].str.replace(x, '')

    return y

输出

    name

    here a th       
    pany    
    there food 

我所期望的:

    name    

    here a this       
    company 
    there food   

参考方案

为了避免多个空格,您可以按空格分割值,过滤出匹配的值,然后再加入:

s = set(data2['words'])
data1['name'] = [' '.join(y for y in x.split() if not y in s) for x in data1['name']]
print (data1)
          name
0  here a this
1      company
2   there food

如果将单词边界replace与正则表达式一起使用,但可以使用多个空格,则可以使用\b\b解决方案:

pat = '|'.join(r"\b{}\b".format(x) for x in data2['words'])
data1['name'] = data1['name'].str.replace('('+ pat + ')', '')
print (data1)
           name
0  here  a this
1       company
2  there   food

所以最后有必要将其删除:

pat = '|'.join(r"\b{}\b".format(x) for x in data2['words'])
data1['name'] = data1['name'].str.replace('('+ pat + ')', '').str.replace(' +', ' ')
print (data1)
          name
0  here a this
1      company
2   there food

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

python pandas:按行对条件进行分组 - python

我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…