Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Multiple Dummy Variables into one Column [duplicate]

Tags:

python

pandas

I would like to convert a table that looks like this:

            Blue    Green    Red
Thing 1     No      Yes      No
Thing 2     Yes     No       No
Thing 3     Yes     No       No

Into this style:

            Color
Thing 1     Green
Thing 2     Blue
Thing 3     Blue

Is there a nice way to do this in python or pandas? And do these table styles have names?

like image 805
The Nightman Avatar asked Oct 19 '25 03:10

The Nightman


2 Answers

Just use idxmax:

df.eq('Yes').idxmax(axis=1)

Output

Thing 1    Green
Thing 2     Blue
Thing 3     Blue
dtype: object
like image 155
Dani Mesejo Avatar answered Oct 21 '25 18:10

Dani Mesejo


If each row has exactly one 'yes', you can do

df.eq('Yes') @ df.columns

Output:

Thing 1    Green
Thing 2     Blue
Thing 3     Blue
dtype: object
like image 20
Quang Hoang Avatar answered Oct 21 '25 16:10

Quang Hoang