Heisenberg
Heisenberg

Reputation: 5299

how to transform categorical dataframe in pandas

My dataframe is below

Sex type 
M    A  
W    B
W    A
M    C

I would like to get below result

M W A B C
1 0 1 0 0
0 1 0 1 0
0 1 1 0 0
1 0 0 0 1

I tried

df['Sex','type'].get_dummies()

But didnt work well.

how can I get this result?

Upvotes: 2

Views: 58

Answers (1)

jezrael
jezrael

Reputation: 862661

I seems you need pandas.get_dummies:

print (pd.get_dummies(df, prefix_sep='', prefix=''))
   M  W  A  B  C
0  1  0  1  0  0
1  0  1  0  1  0
2  0  1  1  0  0
3  1  0  0  0  1

Also if some duplicates in columns names is necessary groupby by columns axis=1 and level=0 and aggregate max:

print (pd.get_dummies(df, prefix_sep='', prefix='').groupby(axis=1, level=0).max())
   A  B  C  M  W
0  1  0  0  1  0
1  0  1  0  0  1
2  1  0  0  0  1
3  0  0  1  1  0

Upvotes: 3

Related Questions