删除括号内的文本

问题描述 投票:0回答:1

我正在处理数据框。在“日期”列中,由于某些原因,某些日期在当月的日期之后的括号中带有数字。

即2010年4月5日(2),>

我想变成:2010年4月5日

是否有一种方法可以消除列中所有行的空格和括号部分?

这是我尝试过的唯一方法,但是我对使用正则表达式非常陌生,所以我不知道如何解决它:

re.sub(" (.)", "", df['Date'])

这是我得到的错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-103-06833d51a3a0> in <module>
      1 import re
----> 2 re.sub(" (.)", "", df['Date'])

~/anaconda3/lib/python3.7/re.py in sub(pattern, repl, string, count, flags)
    190     a callable, it's passed the Match object and must return
    191     a replacement string to be used."""
--> 192     return _compile(pattern, flags).sub(repl, string, count)
    193 
    194 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object

提前感谢!

我正在处理数据框。在“日期”列中,由于某些原因,某些日期在当月的日期之后的括号中带有数字。即2010年4月5日(2),我想转成:...

python regex dataframe
1个回答
0
投票

括号和句号在正则表达式中都有特殊用途,因此,如果要匹配括号,则需要使用\(对其进行显式转义。

© www.soinside.com 2019 - 2024. All rights reserved.