I have a dataframe with a 14K rows. I want to replace a few words in column of my dataframe.
| Bathroom_type |
|---|
| bath |
| baths |
| sharedbaths |
| privatebath |
| sharedbath |
I want to Replace the words – ‘bath’, ‘baths’, and ‘privatebath’ with "Private Bath" and Replace the words – ‘sharedbath’ and ‘sharedbaths’ with "Shared Bath"
I used the below line of code to replace in the cells that contain only bath, but it is replacing the word bath in all the rows, so cell containing ‘sharedbath’ changed to ‘sharedPrivate Bath’.
df['bathroom_type'] = df.bathroom_type.str.replace(r'bath', 'Private Bath')
Please help me to fix my problem. thanks. I’m really new to python so please reply an easy way or detailed explanation of the correct coding. Thanks.
>Solution :
Try this simple approach using lambda and a dictionary containing current string values to be replaced.
r_words = {'bath' : "Private Bath",
'baths' : "Private Bath",
'privatebath' : "Private Bath",
'sharedbaths': "Shared Bath",
'sharedbath': "Shared Bath"}
df['bathroom_type'] = df['bathroom_type'].apply(lambda x: r_words[x])