How to create feature with condition by using where()?

Question:

I am encoding my categorical data in column "Gender" by get_dummies()
Data at begining
Next, I have to create new feature isMale by using where()
This feature should show gender by value(0 and 1), if gender is "female" than isMale equals to 0, and analogical gender="male" than isMale=1

And this feature should swap my "Gender" or just concatenate to my dataset

I don’t get how to use where() method for creating feature

Asked By: Qulymzhanov Nursat

||

Answers:

Use assign and then the np.where

import numpy as np
import pandas as pd

...


df = df.assign(
    isMale=np.where(df['Gender'] == 'Female', 0, 1)
)
Answered By: stefan_aus_hannover

To replace your gender column:

import numpy as np
import pandas as pd


df['Gender'] = np.where(df['Gender'] == "Male", 1, 0)

To add a new column:

import numpy as np
import pandas as pd


df['isMale'] = np.where(df['Gender'] == "Male", 1, 0)
Answered By: nathan liang

you don’t need np.where. since you’re assigning boolean value, just check if Gender= Male is True or False, then convert True/False to int will get you 0 and 1

df['isMale'] = df['Gender'].eq('Male').astype(int)
Answered By: Naveed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.