Find and replace using * equivalent in pandas dataframe

Viewed 49

I want to replace the string "Private room in house" with "Private" in a column in a dataframe

I have tried

df['room'] = df['room'].str.replace("Private[]","Private") 

putting all the various regular expression characters in the [] but nothing works. All I have succeeded in doing is removing the space after Private.

I have looked at re.sub but haven't managed to get anything to work for me. I'm pretty new to Python so this is probably a simple problem but I can't find the answer anywhere

1 Answers

You can use:

df['room'] = df['room'].str.replace('Private.*','Private', regex=True) 

Or with a look behind:

df['room'] = df['room'].str.replace('(?<=Private).*', '', regex=True) 
Related