how i can replace different values in a column to category based on their values

Question:

I have different values in a column, as you can see here. My objective is that if I have the word ‘car’ in any values, I want to change these values to car, if I have the word ‘wedding’ in the value I want to change the value to the wedding. Please help me write the code in python.

I tried this code but it didn’t work:

credit_scoring['purpose']=credit_scoring['purpose'].replace(['building a property','building a real estate'], value= 'real estate')

Also I have different values that I want to change.

Asked By: alars

||

Answers:

You could try first detecting if the substring you are looking for is in the string, and if it is you replace the value for what you want, like this:

credit_scoring = credit_scoring.fillna('')

for i in range(0,len(credit_scoring)):
    if "car" in credit_scoring.loc[i, "purpose"]:
        credit_scoring.loc[i, "purpose"] = "Car"
    elif "wedding" in credit_scoring.loc[i, "purpose"]:
        credit_scoring.loc[i, "purpose"] = "Wedding"

I don’t know if you have NaN’s in your dataframe, but if you have the first line is to fill them with blank spaces, because the method I showed doesn’t work with NaN.

Answered By: Gil Ramos