【问题标题】:How to replace parentheses from a string in pandas dataframe如何从熊猫数据框中的字符串中替换括号
【发布时间】: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


【解决方案1】:

替换除 \w 之外的所有内容。 \w 匹配字母数字字符和下划线,_。

df1['Col1'] = df1['Col1'].str.replace('[^\w]','', regex=True)

0      Test1_2345
1       Test2_123
2    Test3_567_rt
3       Test5_874

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 2018-09-24
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多