0

I have data like this in dataframe

Text Label1 Label2 label3 label4 Labels
Hello my name is john 1 0 1 0

and I want to fill the labels column based on the ones and zeros to be like this

Text Label1 Label2 label3 label4 Labels
Hello my name is john 1 0 1 0 ['Label1','Label3']

How can I do in python?

Belal
  • 111
  • 1
  • 7

1 Answers1

1

Ok, this is an untested suggestion from this answer. Try gathering the appropriate column labels then using DataFrame.apply on a suitable function:

test_cols = [c for c in df.columns if c[:5].lower() == 'label']
test_cols.remove('Labels')

def aggLabels(aSeries):
    return [lab for lab in test_cols if aSeries[lab]==1]

df['Labels'] = df.apply(aggLabels, axis=1)

As I say this is untested; there may be code tweaks required.

Joffan
  • 1,485
  • 1
  • 13
  • 18