Python Changing Textual Values to Numerical Values Output

Viewed 52

I currently have a data set with a bunch of different columns listed below stating "No" or "Yes", "Female" or "Male". I wanted to change the No's and Females to 0 and Yes and Males to 1. I included the picture of what I'm trying to do below. enter image description here The code doesnt error out but the output I'm getting is below. Please help!
enter image description here Null = dF.isnull() .any()

dF = dF.drop(["customerID", "gender", "SeniorCitizen", "Partner", "Dependents", "tenure", "PhoneService", "MultipleLines", "InternetService", "OnlineSecurity", "OnlineBackup", "DeviceProtection", "TechSupport", "StreamingTV", "StreamingMovies", "Contract", "PaperlessBilling", "PaymentMethod", "MonthlyCharges", "TotalCharges", "Churn"], axis=1)

for column in range(len(list(dF.columns.values))):
    for index, row in dF.iterrows():
         if "No" in row[column] or "Female" in row[column]:
            dF.iloc[index, column] = 0
    
         elif "Yes" in row[column] or "Male" in row[column]:
            dF.iloc[index, column] = 1
        
dF.to_excel('Cleaned.xlsx', index=False)
1 Answers

Since you have multiple conditions that you want to modify your variables to, you can use the np.select() function to specify the choices and the outputs for those choices. This is similar to how the case_when() function works in R's dplyr package.

for col_name in df.columns:
    df[col_name] = np.select([df[col_name] == x for x in ['No','Female','Yes','Male']],
                                                         [0   , 0      , 1   , 1    ])

https://numpy.org/doc/stable/reference/generated/numpy.select.html

Related