Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace a word in particular cells of a dataframe without changing the same word in other cells in pandas?

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading