Reputation: 1
The dataframe I'm using has a column named 'Sex' filled with 'male'/ 'female'. I need to change 'male'/'female' for a number, namely 0 or 1.
I'm trying the following code
result = df.apply(lambda x: 1 if x == 'male' else 0, )
and the error is
AttributeError: 'str' object has no attribute 'Sex'
Upvotes: 0
Views: 76
Reputation: 2477
label_dict = {'male':0, 'female':1}
df['Sex'] = df.category.replace(label_dict)
You could use a dictionary that maps the values in the dataframe column to their corresponding values in the dictionary.
Upvotes: 0
Reputation: 1560
Version using .replace
df['Sex'] = df['Sex'].replace({'male': 1, 'female': 0})
Version using .map
df['Sex'] = df['Sex'].map({'male': 1, 'female': 0})
Version using boolean casting
df['Sex'] = (df['Sex'] == 'male').astype(int)
This last version has the advantage to make all values different than male as 0
Upvotes: 0