0

I have data frame containing the IDs of animals and types they belong to as given below

ID  Class
1   1
2   1
3   0
4   4
5   3
6   2
7   1
8   0

I want convert it to a new style with the classes on the header row as follows.

ID  0   1   2   3   4
1       1           
2       1           
3   1               
4                   1
5               1   
6           1       
7       1           
8   1               

Can you help me to do it with python

1

1 Answer 1

1

See get_dummies():

>>> print df

   ID  Class
0   1      1
1   2      1
2   3      0
3   4      4
4   5      3
5   6      2
6   7      1
7   8      0

>>> df2 = pd.get_dummies(df, columns=['Class'])
>>> print df2

   ID  Class_0  Class_1  Class_2  Class_3  Class_4
0   1        0        1        0        0        0
1   2        0        1        0        0        0
2   3        1        0        0        0        0
3   4        0        0        0        0        1
4   5        0        0        0        1        0
5   6        0        0        1        0        0
6   7        0        1        0        0        0
7   8        1        0        0        0        0

And if you want to get rid of "Class_" in the column headers, set both prefix and prefix_sep to the empty string:

df2 = pd.get_dummies(df, columns=['Class'], prefix='', prefix_sep='')

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. I get float values in the columns when I do it. Can you help me with it?
They are numpy.float64 for me too (though my displayed output doesn't show ".0"s, which is different from you for some reason). Do you just want to change the display, or do you want to change the underlying data type? Either way, I think you can find your answer here: stackoverflow.com/questions/21291259/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.