Steven Garboden
Steven Garboden

Reputation: 77

how to use an aggregate on pandas df column and retain original df

I want to apply an aggregate to the pet age column, but retain the original df columns that disappear when this agg is applied. From the image, How do I bring the other columns to the resulting df when aggregate is applied.

I could also convert the other columns to numeric type, or merge this with the original? Thanks!

enter image description here

Upvotes: 2

Views: 250

Answers (1)

Parfait
Parfait

Reputation: 107697

Simply use transform for inline aggregation or any group-specific computations that returns a like-indexed object:

merge['pet_age_group_mean'] = merge.groupby('user_id')['pet_age'].transform('mean')

Upvotes: 2

Related Questions