Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pivot one colum with n categories into n binary values column?

I have a following dataframe:

id gender name status
1 M John Withdrawn
2 F Mary Pass
10 F Kate Fail

And I want to transform it into a dataframe like this:

id gender name Withdrawn Pass Fail
1 M John 1 0 0
2 F Mary 0 1 0
10 F Kate 0 0 1

Is something like this possible with using functions like pivot_table or is it necessary to write a function and then loop through every row and append a value to corresponding column?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As simple as using dummy variables:

df = pd.get_dummies(df, columns=['status'])
df = df.drop(columns = ['status'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading