Skip to content
Advertisement

How do I average values of a group range in pandas? [closed]

I have this Dataframe. I want to make age range 1-5, 6-10, 11-15, etc and set all values in this range by their mean.

JavaScript

Now I want to add a column ageGroup which will contain the mean of the required range. Here 1-5 is a range. so all of the ages between these will mean value. Here, (5+2+5+1) // 4 = 3. Similarly, for range 11-15 will be (12+13) // 2 = 12.

So, the expected output is.

JavaScript

Advertisement

Answer

You can use pd.cut to bin the data and then you can use with groupby:

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement