Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to achieve this concatenation in Pandas?

I have a dataframe df :-

tray bag ball
0 1 1
0 1 0
1 1 0
0 0 1
0 0 0

I want to add a column Presence in the dataframe df seperated by comma this way :-

tray bag ball Presence
0 1 1 bag,ball
0 1 0 bag
1 1 0 tray,bag
0 0 1 ball
0 0 0 No Presence

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use DataFrame.dot with mask – compare columns by 1 with columns names and separator, last replace empty string:

df['Presence'] = df.eq(1).dot(df.columns + ',').str[:-1].replace('','No Presence')
print (df)
   tray  bag  ball     Presence
0     0    1     1     bag,ball
1     0    1     0          bag
2     1    1     0     tray,bag
3     0    0     0  No Presence
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading