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.
CodePudding user response:
You could map
every value in 'bathroom_type'
column as explain here.
"Used for substituting each value in a Series
with another value, that may be derived from a function, a dict or a Series
".
r_words = {'bath' : "Private Bath",
'baths' : "Private Bath",
'privatebath' : "Private Bath",
'sharedbaths': "Shared Bath",
'sharedbath': "Shared Bath"}
df['bathroom_type'] = df['bathroom_type'].map(r_words)