Search code examples
pythonpandaspandas-groupbydummy-variable

From Dummy to a List pandas


I have a dataframe with many dummy variables. Instead of having a lot of different dummy columns, I want only one column and each row needs to contain a string with only the dummy variable equal to 1.

index  a   b   c 
0      1   1   1  
1      0   0   1   

Output:

index  dummies  
0      ['a','b','c']  
1      ['c']

Solution

  • dummies = df.apply(lambda x: [col for col in df.columns if x[col] == 1], axis=1)