'Create a List of Column headers if a row in a column contains a 1

That's my first question, I tried to find an answer to it, so I hope that question don't spam the Q&A.

I want all names of the column headers containing a 1 in a new column as a list.

I have framed the desired result in red:

Column A to G are the existing columns and I try to create column H

Column A to G are the existing columns and I try to create column H

I hope my English is not too bad to describe the problem correctly

Many thanks in advance for helpful tips

EDIT: I have a list thanks to rhug123, but I would like a string. I have tried the following, unfortunately I get an error message. Would somebody be so kind and help me?

    df['new'] = df.stack().loc[df.stack().eq(1)].reset_index(level=1).groupby(level=0)['level_1'].agg(list)

separator = ","
df["new2"] = separator.join(df["new"])

I got the following error message:

df["new2"] = separator.join(df["new"])

TypeError: sequence item 0: expected str instance, list found



Solution 1:[1]

Here is another way using stack() and groupby()

df['new'] = df.stack().loc[df.stack().eq(1)].reset_index(level=1).groupby(level=0)['level_1'].agg(list)

Here are a few other ways:

df.mul(df.columns).where(df.eq(1)).stack().groupby(level=0).agg(','.join)

df.where(df.eq(1)).stack().rename_axis([None,'cars']).reset_index(level=1).groupby(level=0)['cars'].agg(','.join)

df.dot(df.columns).str.findall('|'.join(df.columns)).str.join(',')

Solution 2:[2]

Its better to clear out the question with an example in text of your question like the one you showed with a photo:

df = df.fillna(0)
df = df.assign(newcol = lambda x: x.apply(lambda s: ','.join(np.array(df.columns)[s.astype(bool)]),axis=1)) 

The result would be:

   BMW  Smart  Mini  Mercedes  Porsche                          new
0    1      0     0         0        1                  BMW,Porsche
1    0      1     1         1        1  Smart,Mini,Mercedes,Porsche

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2