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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How 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.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived