N27
N27

Reputation: 31

str.replace with special character "(*)"

I have some column s in a dataframe with (*) on some of the data headers. When I do

data.columns = data.columns.str.replace('(*)','')

I get the following error.

  File "C:\Users\ED397JT\Anaconda3\lib\site-packages\pandas\core\strings\object_array.py", line 156, in _str_replace
    pat = re.compile(pat, flags=flags)

  File "C:\Users\ED397JT\Anaconda3\lib\re.py", line 252, in compile
    return _compile(pattern, flags)

  File "C:\Users\ED397JT\Anaconda3\lib\re.py", line 304, in _compile
    p = sre_compile.compile(pattern, flags)

  File "C:\Users\ED397JT\Anaconda3\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)

  File "C:\Users\ED397JT\Anaconda3\lib\sre_parse.py", line 948, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)

  File "C:\Users\ED397JT\Anaconda3\lib\sre_parse.py", line 443, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,

  File "C:\Users\ED397JT\Anaconda3\lib\sre_parse.py", line 834, in _parse
    p = _parse_sub(source, state, sub_verbose, nested + 1)

  File "C:\Users\ED397JT\Anaconda3\lib\sre_parse.py", line 443, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,

  File "C:\Users\ED397JT\Anaconda3\lib\sre_parse.py", line 668, in _parse
    raise source.error("nothing to repeat",

error: nothing to repeat

What can I do?

Upvotes: 0

Views: 151

Answers (1)

Stanley
Stanley

Reputation: 320

str.replace takes a regular expression and * is a metacharacter it is trying to interpret. Try escaping it like so:

data.columns.str.replace('(\*)', '')

or indicate that you aren't using regex:

data.columns.str.replace('(*)', '', regex=False)

Upvotes: 1

Related Questions