Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping column values together

Tags:

python

pandas

I have a dataframe like so:

Class  price  demand
1       22       8
1       60       7
3       32       14
2       72       9
4       45       20
5       42       25

What I'd like to do is group classes 1-3 in one category and classes 4-5 in one category. Then I'd like to get the sum of price for each category and the sum of demand for each category. I'd like to also get the mean. The result should look something like this:

Class   TotalPrice   TotalDemand   AveragePrice  AverageDemand
P          186            38           46.5          9.5   
E          87             45           43.5          22.5

Where P is classes 1-3 and E is classes 4-5. How can I group by categories in pandas? Is there a way to do this?

like image 524
user2896120 Avatar asked Jun 08 '26 23:06

user2896120


1 Answers

In [8]: df.groupby(np.where(df['Class'].isin([1, 2, 3]), 'P', 'E'))[['price', 'demand']].agg(['sum', 'mean'])
Out[8]: 
  price       demand      
    sum  mean    sum  mean
E    87  43.5     45  22.5
P   186  46.5     38   9.5
like image 148
chrisaycock Avatar answered Jun 11 '26 12:06

chrisaycock