3

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 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.