Home > Back-end >  Convert variables from dataframe into nums
Convert variables from dataframe into nums

Time:04-15

I need to convert my Sex and Embarked values into num. My solution doesn't work properly, it changes values for all columns

titset[titset['Sex']=='male'] = 2
titset[titset['Sex']=='female'] = 1
titset

Piece of my dataframe:

import pandas as pd
id = [1,2,3,4,5,6,7,8,9,10]
data = {
'Fare': ['male', 'female', 'male', 'male', 'female','male','male','female','male','female'],
'Embarked': ['S','C','Q','S','S','S','C','C','S','S']
}
titanic = pd.DataFrame(data=data, index=id)
titanic

CodePudding user response:

Use Series.map:

titanic["Fare"] = titanic["Fare"].map({"male": 2, "female": 1})

CodePudding user response:

you can use code from @Code_Different or you can use DataFrame.replace function

titanic = titanic.replace({'Fare':{'male':2,'female':1'}})
  • Related