Python 替换位置处的字符串-未知标志
我的数据如下所示:Python 替换位置处的字符串-未知标志,python,pandas,numpy,Python,Pandas,Numpy,我的数据如下所示: df.head() CLUID STEP 9995 1998-10-27-03.18.54.256142 orders/sign() 9996 9012-03-22-00.56.55.724614 settings/user(?section=:section) 9997 9012-03-22-00.56.55.724614 settings/plugins 9998 1998-10-27-03.18.54.256142 saving/t
df.head()
CLUID STEP
9995 1998-10-27-03.18.54.256142 orders/sign()
9996 9012-03-22-00.56.55.724614 settings/user(?section=:section)
9997 9012-03-22-00.56.55.724614 settings/plugins
9998 1998-10-27-03.18.54.256142 saving/transactions
9999 9012-03-22-00.56.55.724614 settings/electronicstorage
我想从列步骤中删除特定的子字符串
我试过:
df['STEP'] = df['STEP'].replace({'(?section=:section)': ''}, regex=True)
其中提出:
错误:位置3处的标志未知
预期产出:
CLUID STEP
9995 1998-10-27-03.18.54.256142 orders/sign()
9996 9012-03-22-00.56.55.724614 settings/user
9997 9012-03-22-00.56.55.724614 settings/plugins
9998 1998-10-27-03.18.54.256142 saving/transactions
9999 9012-03-22-00.56.55.724614 settings/electronicstorage
非常感谢您的帮助。
(?aiLmsux)
(集合“a”、“i”、“L”、“m”、“s”、“u”、“x”中的一个或多个字母)[……] (还有
(?aiLmsux imsx:…)
)
这就是为什么第三个位置是错误的,(位置0-1-2上的?s
可能是有效的,但是下面的e
不是。(?section=:section)
不是有效的正则表达式
replace()
import pandas
df=pandas.DataFrame({"CLUID":["1998-10-27-03.18.54.256142","9012-03-22-00.56.55.724614","9012-03-22-00.56.55.724614"],
"STEP":["orders/sign()","settings/user(?section=:section)","settings/plugins"]})
print(df)
df['STEP'] = df['STEP'].replace({'\(\?section=:section\)': ''}, regex=True)
print(df)
我知道晚了几分钟,但值得一提的是,括号也必须转义。使用re.sub
可能会有所帮助。反斜杠将字符“?”视为特殊字符
import pandas as pd
df = pd.DataFrame({'STEP': ["settings/user(?section=:section)", "orders/sign(/:orderIds)"]})
df['STEP'].apply(lambda x: re.sub('(\?section=:section)', '', str(x)))
实际上,这也适用于replace
:
df['STEP'] = df['STEP'].replace({'(\?section=:section)': ''}, regex=True)
请发布您的预期输出。正如@MayankPorwal所问:您希望发生什么?请将预期输出添加到问题中。@MayankPorwal已编辑。在不使用regex=True
@tevemadar的情况下尝试。它什么都不做。以前已经尝试过。但是我应该如何处理它?有什么解决方法吗?@StanislavJirák到目前为止,我无法说出代码是什么应该这样做。我想从列中删除上面的子字符串。我编辑了问题。