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

Forming a condition based on a Dataframe groupby object, but getting more columns than expected

So i have the following line of code.

df[['Steps','CampaignSource','UserId']].groupby(['Steps','CampaignSource']).apply(lambda x : x.nunique() if x.name[0] != '9.2-Finalizado' else x.count())

Which as can see i apply a condition based on a groups key specifically the first one. But the thing is i get this weird end result, which basically gives me two more columns than i would like.

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

enter image description here

Any clues on the why, i would like that only UserId returns. if necessary i can provide a sample df.

>Solution :

You can slice the GroupBy object:

(df.groupby(['Steps','CampaignSource'])['UserId']
   .apply(lambda x : x.nunique() if x.name[0] != '9.2-Finalizado' else x.count())
)

or for a DataFrame:

(df.groupby(['Steps','CampaignSource'])[['UserId']]
   .apply(lambda x : x.nunique() if x.name[0] != '9.2-Finalizado' else x.count())
)
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