【发布时间】:2021-12-29 18:21:07
【问题描述】:
假设我有一个这样的数据框:
Col1
0 Test1_2345)
1 Test2_(123
2 Test3_567)_rt
3 Test5_874)
如何从 Col1 中的字符串中替换 "(" 和 ")" 并拥有这样的数据框:
Col1
0 Test1_2345
1 Test2_123
2 Test3_567_rt
3 Test5_874
我试过这个,但它不起作用:
df['Col1'] = df['Col1'].replace("(","",regex=True)
df['Col1'] = df['Col1'].replace(")","",regex=True)
【问题讨论】:
-
括号是正则表达式中的实际标记,如果您的字面意思是括号,则需要转义它们。
df.Col1.str.replace('\(|\)','')在这种情况下,左或右 -
也可以做一个字符类而不转义
df['Col1'] = df['Col1'].replace('[()]', '', regex=True) -
非常感谢@Chris 和 henryecker,这也有效
标签: python python-3.x pandas dataframe