1

I need do create some additional columns to my table or separate table based on following:

I have a table

enter image description here

and I need to create additional columns where the column indexes (names of columns) will be inserted as values. Like this:

enter image description here

How to do it in pandas? Any ideas? Thank you

0

1 Answer 1

3

If need matched columns only for 1 values:

df = (df.set_index('name')
        .eq(1)
        .dot(df.columns[1:].astype(str) + ',')
        .str.rstrip(',')
        .str.split(',', expand=True)
        .add_prefix('c')
        .reset_index())
print (df)

Explanation:

Idea is create boolean mask with True for values which are replaced by columns names - so compare by DataFrame.eq by 1 and used matrix multiplication by DataFrame.dot by all columns without first with added separator. Then remove last traling separator by Series.str.rstrip and use Series.str.split for new column, changed columns names by DataFrame.add_prefix.

Another solution:

df1 = df.set_index('name').eq(1).apply(lambda x: x.index[x].tolist(), 1)
df = pd.DataFrame(df1.values.tolist(), index=df1.index).add_prefix('c').reset_index()
Sign up to request clarification or add additional context in comments.

1 Comment

I just need to have a zoomed look to the code and understand it. Big, big thanks!!

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.