Skip to content Skip to sidebar Skip to footer

Converting Multiple Dummy Variables Into One Column

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

Solution 1:

Just use idxmax:

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

Output

Thing 1    Green
Thing 2     Blue
Thing 3     Blue
dtype:object

Solution 2:

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

Solution 3:

Use:

df.where(df.eq('Yes')).stack().reset_index(level=1)['level_1']

Thing 1    Green
Thing 2     Blue
Thing 3     Blue
Name: level_1, dtype: object

Post a Comment for "Converting Multiple Dummy Variables Into One Column"