Q:

How to change values in a column into binary?

New to python and I am stuck at this. My CSV file contain this:
Sr,Gender
1,Male
2,Male
3,Female

Now I want to convert the Gender values into binary so the the file will look something like:
Sr,Gender
1,1
2,1
3,0

So, I imported the CSV file as data and ran this code:
data["Gender_new"]=1
data["Gender_new"][data["Gender"]=="Male"]=0
data["Gender_new"]=1=data["Gender_new"].astype(float)

But I got the error ValueError: could not convert string 'Male' to float:
What am I doing wrong and how can I make this work?
Thanks

A:

Try this:
import pandas as pd

file = open("your.csv", "r")

data = pd.read_csv(file, sep = ",")

gender = {'male': 1,'female': 0}

data.Gender = [gender[item] for item in data.Gender]
print(data)

Or
data.Gender[data.Gender == 'male'] = 1
data.Gender[data.Gender == 'female'] = 0
print(data)

