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

To merge the values of common columns in a data frame

There is one data frame consisting of three columns: group, po, and part

import pandas as pd

df = pd.DataFrame({'group':[1,1,1,1,1,1,2,2,2,2,3,3],
       'po':['1a','1b','','','','','2a','2b','2c','','3a',''],
       'part':['a','b','c','d','e','f','g','h','i','j','k','l']})

enter image description here

by group column,
Po columns are common parts and I want to display them continuously using a slash(‘/’)

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

like below dataframe

enter image description here

What should I do?

>Solution :

You can group the po values by group, aggregating them using join (with filter to discard empty values):

df['po'] = df.groupby('group')['po'].transform(lambda g:'/'.join(filter(len, g)))
df

Output:

    group        po part
0       1     1a/1b    a
1       1     1a/1b    b
2       1     1a/1b    c
3       1     1a/1b    d
4       1     1a/1b    e
5       1     1a/1b    f
6       2  2a/2b/2c    g
7       2  2a/2b/2c    h
8       2  2a/2b/2c    i
9       2  2a/2b/2c    j
10      3        3a    k
11      3        3a    l
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