Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by and dummies in pandas

Tags:

python

pandas

I have a pandas dataframe: key val

A    1

A    2

B    1

B    3

C    1

C    4

I want to get do some dummies like this:

A  1100

b  1010

c  1001
like image 828
burness duan Avatar asked Apr 16 '16 16:04

burness duan


1 Answers

Here is something that I used for my case and tried to apply on yours as far as I could understand the problem

df
  key1  key2
0    A     1
1    A     2
2    B     1
3    B     3
4    C     1
5    C     4

pd.get_dummies(df, columns=['key2']).groupby(['key1'], as_index=False).sum()

Output:

  key1  key2_1  key2_2  key2_3  key2_4
0    A     1.0     1.0     0.0     0.0
1    B     1.0     0.0     1.0     0.0
2    C     1.0     0.0     0.0     1.0
like image 129
Shivam Shakti Avatar answered Sep 28 '22 01:09

Shivam Shakti