如何使用Pandas从给定的字符串中删除子字符串 [英] How can I remove a substring from a given String using Pandas

查看:71
本文介绍了如何使用Pandas从给定的字符串中删除子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始分析数据框,并希望删除所有不包含的子字符串

Recently I started to analyse a data frame and I want to remove all the substrings that don't contain

('Aparelho Celular','Internet (Serviços e Produtos)','Serviços Telefônicos Diversos','Telefonia Celular','Telefonia Comunitária ( PABX, DDR, Etc. )','Telefonia Fixa','TV por Assinatura','Televisão / Aparelho DVD / Filmadora','Telemarketing')

但是当我使用这种语法时-

But when I use this syntax-

df = df[~df["GrupoAssunto"].str.contains('Aparelho Celular','Internet (Serviços e Produtos)','Serviços Telefônicos Diversos','Telefonia Celular','Telefonia Comunitária ( PABX, DDR, Etc. )','Telefonia Fixa','TV por Assinatura','Televisão / Aparelho DVD / Filmadora','Telemarketing')]

我收到此错误:

TypeError: contains() takes from 2 to 6 positional arguments but 10 were given

推荐答案

只需在启用正则表达式的情况下通过 | 分隔不同的单词.这是用于搜索包含contains的多个字符串的正确语法. re 安全转换涉及转义括号和任何其他特殊字符.

Just seperate the different words by | with regex turned on. This is the proper syntax for searching for multiple strings with contains. The re safe conversion deals with escaping the parenthesis and any other special characters.

bad_strings = ['Aparelho Celular','Internet (Serviços e Produtos)','Serviços Telefônicos Diversos','Telefonia Celular','Telefonia Comunitária ( PABX, DDR, Etc. )','Telefonia Fixa','TV por Assinatura','Televisão / Aparelho DVD / Filmadora','Telemarketing']
safe_bad_strings = [re.escape(s) for s in bad_strings]
df = df[~df["GrupoAssunto"].str.contains('|'.join(safe_bad_strings), regex=True]

发生错误是因为10个字符串都作为参数传递给contains.但是contains期望的模式不止一种,因此会引发错误.

Your error is occurring because the 10 strings are all being passed as arguments to contains. But contains doesn't expect more than one pattern so it is throwing an error.

这篇关于如何使用Pandas从给定的字符串中删除子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆