Issue
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
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
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(',')
Answered By - rhug123
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.