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


enter image description here
pls see attached image
I have different values in a column, for example, 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…
pls help to write the code in python

I tried this code but it didn’t work , also i have different values that I want to change

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

Asked By: alars



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