Bottom Page

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!
Quote
#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),
   )
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Question about the groupby function new_to_python 7 171 Feb-09-2020, 07:52 AM
Last Post: perfringo
  conditional groupby and aggregation on the conditioned group values harrshu 1 250 Oct-20-2019, 10:24 AM
Last Post: DeaD_EyE
  'Age' categorical (years -months -days ) to numeric Smiling29 4 303 Oct-17-2019, 05:26 PM
Last Post: Smiling29
  categorical encoder Scott 0 819 May-19-2018, 03:38 AM
Last Post: Scott
  groupby and window function lravikumarvsp 3 830 May-13-2018, 06:24 AM
Last Post: buran
  groups attribute of a groupby object question smw10c 2 1,711 Apr-27-2017, 03:18 PM
Last Post: smw10c

Forum Jump:


Users browsing this thread: 1 Guest(s)