How to insert a string value in a list that is in a cell in pandas dataframe?

Viewed 223

I am trying to create tags out of dummy variables in my dataset. I have created a column "Tags_col" and everytime my nested for-loop iterates over every row, if there is a 1 for a certain category, I would like that category to be included in a list in the tags_col for every row.

Something like this:

Dog   Cat   Rabbit   Tags_col
 0     1      1      ['Cat','Rabbit']
 1     0      0      ['Dog']

So far I have this:

for x in range(len(df)):
   for col in df.columns:
       if df.loc[x,col] == 1:
           df.loc[x, "Tags_col"] = col

However, this is only attaching the first category the for-loop finds in the Tags_col.

Thank you.

1 Answers

Use list comprehension with boolean DataFrame by compare by 1 and filter array created from columns names:

cols = df.columns.to_numpy()
df['Tags_col'] = [list(cols[x]) for x in df.eq(1).to_numpy()]
print (df)

   Dog  Cat  Rabbit       Tags_col
0    0    1       1  [Cat, Rabbit]
1    1    0       0          [Dog]

If performance is not important use DataFrame.apply:

df['Tags_col'] = df.apply(lambda x: list(x.index[x==1]), axis=1)
print (df)
   Dog  Cat  Rabbit       Tags_col
0    0    1       1  [Cat, Rabbit]
1    1    0       0          [Dog]
Related