Python Forum
Using groupby on non-categorical values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using groupby on non-categorical values
#1
Hello everybody, I have a data set:
animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]})
Output:
kind height weight 0 cat 9.1 7.9 1 dog 6.0 7.5 2 cat 9.5 9.9 3 dog 34.0 198.0
It is simple enough to use groupby to, say get the statistics of height and weight by kind:

animals.groupby("kind").agg(
       min_height=('height', 'min'),
        max_height=('height', 'max'),
      average_weight=('weight', np.mean),
   )
    
Output:
min_height max_height average_weight kind cat 9.1 9.5 8.90 dog 6.0 34.0 102.75
My challenge is if I want to get the mean of weight of all animals that has a height between 9.0 and 10.0? Can I still use groupby? Thanks!
Reply
#2
You can filter entire dataframe first, e.g.

animals[(9<animals.height)&(animals.height<10)].groupby("kind").agg(
       min_height=('height', 'min'),
        max_height=('height', 'max'),
      average_weight=('weight', np.mean),
   )
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  change numerical values to categorical names JoeOpdenaker 3 2,898 Nov-02-2020, 01:32 PM
Last Post: DeaD_EyE
  conditional groupby and aggregation on the conditioned group values harrshu 1 1,994 Oct-20-2019, 10:24 AM
Last Post: DeaD_EyE
  'Age' categorical (years -months -days ) to numeric Smiling29 4 2,874 Oct-17-2019, 05:26 PM
Last Post: Smiling29
  categorical encoder Scott 0 2,654 May-19-2018, 03:38 AM
Last Post: Scott

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020