Convert categorical column into specific integers

Viewed 153

I have a bunch of dataframes with one categorical column defining Sex (M/F). I want to assign integer 1 to Male and 2 to Female. I have the following code that cat codes them to 0 and 1 instead

df4["Sex"] = df4["Sex"].astype('category')
df4.dtypes
df4["Sex_cat"] = df4["Sex"].cat.codes
df4.head()  

But I need specifically for M to be 1 and F to be 2. Is there a simple way to assign specific integers to categories?

3 Answers

IIUC:

df4['Sex'] = df4['Sex'].map({'M':1,'F':2})

And now:

print(df4)

Would be desired result.

If you need to impose a specific ordering, you can use pd.Categorical:

c = pd.Categorical(df["Sex"], categories=['M','F'], ordered=True)

This ensures "M" is given the smallest value, "F" the next, and so on. You can then just access codes and add 1.

df['Sex_cat'] = c.codes + 1

It is better to use pd.Categorical than astype('category') if you want finer control over what categories are assigned what codes.

You can also use lambda with apply:

df4['sex'] = df4['sex'].apply(lambda x : 1 if x=='M' else 2)
Related