我有以下列表和DataFrame:
mylist = ['foo', 'bar', 'baz']
df = pd.DataFrame({'Col1': ['fooThese', 'barWords', 'baz are', 'FOO: not', 'bAr:- needed'],
'Col2': ['Baz:Neither', 'Foo Are', 'barThese', np.nan, 'but this is fine']})
我想替换mylist中的字符串(如果在DataFrame中找到)。
我可以使用以下正则表达式模式替换其中一些:
pat = '|'.join([r'\b{}'.format(w) for w in mylist])
df2 = df.replace(pat, '', regex=True)
但是,这并不能放置所有实例。我想要的输出如下:
Col1 Col2
0 These Neither
1 Words Are
2 are These
3 not NaN
4 needed but this is fine
参考方案
您必须使用?i
regex标志,这使您的替换不区分大小写,还应删除特殊字符:
mydict = {f'(?i){word}': '' for word in mylist}
df2 = df.replace(mydict, regex=True).replace('[:-]', '', regex=True)
Col1 Col2
0 These Neither
1 Words Are
2 are These
3 not NaN
4 needed but this is fine
或者,您可以将特殊字符添加到词典中,这样就不必两次调用DataFrame.replace
了:
mydict = {f'(?i){word}': '' for word in mylist}#.update({'[:-]': ''})
mydict['[:-]'] = ''
df2 = df.replace(mydict, regex=True)
Col1 Col2
0 These Neither
1 Words Are
2 are These
3 not NaN
4 needed but this is fine
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…