How to convert a pandas dataframe from a string based categorical column to a numeric representation

Clash Royale CLAN TAG#URR8PPPHow to convert a pandas dataframe from a string based categorical column to a numeric representation
I have a column in a dataframe which looks like this:
df['label']
['some_label', 'some_label', 'a_diff_label', 'a_diff_label',...]
I want it to convert it to something like this:
[1,1,0,0,...]
2 Answers
2
Since the similar question I found was very complex and hard to understand, I am posting a simple answer.
Just do this:
df['label'] = (df['label'] == 'some_label').astype(int)
There are lot of ways to achieve this (etc, factor)
pd.Series(['some_label', 'some_label', 'a_diff_label', 'a_diff_label']).astype('category').cat.codes
Out[19]:
0 1
1 1
2 0
3 0
dtype: int8
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.