Your regex is matching on all - characters:
In [48]:
df_raw.replace(['-','\*'], ['0.00','0.00'], regex=True)
Out[48]:
A B
0 1.00 1.0
1 0.001 0.0045.00
2 NaN 0.00
If you put additional boundaries so that it only matches that single character with a termination then it works as expected:
In [47]:
df_raw.replace(['^-$'], ['0.00'], regex=True)
Out[47]:
A B
0 1.00 1.0
1 -1 -45.00
2 NaN 0.00
Here ^ means start of string and $ means end of string so it will only match on that single character.
Or you can just use replace which will only match on exact matches:
In [29]:
df_raw.replace('-',0)
Out[29]:
A B
0 1.00 1.0
1 -1 -45.00
2 NaN 0
Answer from EdChum on Stack Overflowpython - pandas: Dataframe.replace() with regex - Stack Overflow
python .replace() regex - Stack Overflow
python - What does the regex parameter in .replace() function mean - Stack Overflow
pandas .replace not working
Hello Very new to pandas. Trying to replace ampersand in my excel file
Why did I have to add regex=True to get this to work. It wouldn’t update otherwise.
df = df.replace(‘%26’ , ‘&’ , regex = True)
No. Regular expressions in Python are handled by the re module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
str_output = re.sub(regex_search_term, regex_replacement, str_input)
In order to replace text using regular expression use the re.sub function:
sub(pattern, repl, string[, count, flags])
It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.
Examples
>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'
>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'
This is genuinely driving me crazy.
I have a data frame of unit prices in string format i'm trying to get them to a float
item_df['Unit Price'] = item_df['Unit Price'].replace('$','')and all the '$' are still there.
THEN when I do this:
item_df['Unit Price'][1] = item_df['Unit Price'][1].replace('$','')The '$' is gone from that index ಠ_ಠ. What the hell is going on?? Am I taking crazy pills or missing some fundamental concept?
Any help would be much appreciated.
Thanks,