我正在尝试弄清楚如果列中包含某个字符串,则如何删除字符串和括号。
所以在我的专栏中,我可以有两个包含这样的方括号的字符串
col a
this is the text(text it is) and other information (COO: warning) some other information
我能做的是删除所有文本和方括号。但是,我该如何删除包含COO的字符串和括号:??
cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].str.replace(r"\(.*?\)","")
我可以修改上面的代码行只是为了删除并用COO进行输入吗??
答案 0 :(得分:3)
您可以将括号内的术语作为目标,括号中还应包含文本cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].str.replace(r'\([^)]*COO.*?\)', '')
,例如
\( match literal (
[^)]* then match zero or more non ) characters
COO match 'COO'
.*? match remaining content up until the first
\) literal closing )
正则表达式模式的解释:
{{1}}
答案 1 :(得分:0)
cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].apply(lambda string: string.replace("(","").replace(")","") if "COO" in string else string)