Python - Pandas groupby agg

Viewed 194

I have a simple dataframe (df) like shown below:

index Job  Person 
1     j1   Cathy
2     j2   Mark
3     j3   Cathy
4     j4   Steve
5     j5   Cathy

I would like to convert the above dataframe as:

Person CountJob  JobDetails
Cathy     3      j1;j3;j5
Mark      1      j2
Steve     1      j4

I can partially solve this using groupby :

final = df.groupby('Person').agg(
        CountJob=pd.NamedAgg(column='Job',aggfunc="count"),
        )

I am struggling to get the format for the last column 'JobDetails'. I am guessing I can use the lambda function but I just don't know how!

1 Answers

Try:

df.groupby('Person').agg(CountJob=('Job','count'),
                         JobDetails=('Job',';'.join)
                        )
Related