Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dummies without prefix?

Tags:

pandas

I want to get dummies from two different columns, but without any prefix.

Data illustration:

   X    Y
 123  AAA
 456  BBB
 123  AAA
 789  CCC

Expected result:

   X    Y  789  456  123  CCC  BBB  AAA
 123  AAA    0    0    1    0    0    1
 456  BBB    0    1    0    0    1    0
 123  AAA    0    0    1    0    0    1
 789  CCC    1    0    0    1    0    0
like image 868
qwerty Avatar asked Dec 31 '22 12:12

qwerty


1 Answers

Use get_dummies with prefix='' and prefix_sep='' parameters. Also if it is possible some of the columns are numeric convert them to strings:

df = df.join(pd.get_dummies(df.astype(str), prefix='', prefix_sep=''))
print(df)

     X    Y  123  456  789  AAA  BBB  CCC
0  123  AAA    1    0    0    1    0    0
1  456  BBB    0    1    0    0    1    0
2  123  AAA    1    0    0    1    0    0
3  789  CCC    0    0    1    0    0    1
like image 101
jezrael Avatar answered Feb 24 '24 16:02

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!