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

pandas groupby concatination based on a condition

I have a dataframe like below, and I am trying to join the names, when the class is non empty,

Name   class score
kumar   ""    ""
ram     10    14
ravi    ""    ""
tej     ""    ""
om      12    15

my desired output is,

Name      class score
kumarram    10    14
ravitejom   12    15

I tried groupby class, and adding as a new series but the length is not matching,

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

my code:
    df['g1'] = df['class'].ne("").cumsum()
    df.loc[df["class"].ne(""), "Name"] = df.groupby("g1").apply(lambda x: " ".join(x["Name"].values)

>Solution :

You are correct to find blocks with cumsum on negate condition. Here however, you can reverse the series before cumsum, so blocks are count from bottom up:

blocks = df['score'].ne('""')[::-1].cumsum()
df.groupby(blocks).agg({
    'Name':''.join,
    'class':'last',
    'score':'last'
})

Output:

            Name class score
score                       
1      ravitejom    12    15
2       kumarram    10    14
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