【发布时间】:2019-07-16 16:59:16
【问题描述】:
类似问题:Replacing part of string in python pandas dataframe
但它不会工作!?
帕纳斯 23.4
给定以下 df 列:
Expression
XYZ&(ABC|DEF)
(HIJ&FTL&JKK)&(ABC|DEF)
(FML|AXY|AND)&(ABC|DEF)
我想去除每列中可能存在的子字符串。
flag = '(ABC|DEF)'
andFlag = '&' + flag #the reasoning for doing this is that 'flag' may change
#Below are all different ways I have tried to achieve this, none have worked.
df['Expression'] = df['Expression'].replace(andFlag, '', regex=True)
df['Expression'] = df['Expression'].apply(lambda x: re.sub(andFlag, '', x))
df['Expression'] = df['Expression'].replace(to_replace=andFlag, value= '', regex=True)
df['Expression'] = df['Expression'].str.replace(andFlag, '')
df['Expression'] = df['Expression'].str.replace(andFlag, '', regex=True)
无论有没有regex=True,我都尝试过所有这些功能,但均无济于事。
预期输出:
Expression
XYZ
(HIJ&FTL&JKK)
(FML|AXY|AND)
我想弄清楚这一点有点疯狂,它看起来如此简单明了。
【问题讨论】: