Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas plot mean values from corresponding unique id values

This is my csv file. I want to find the mean cost for each unique ids.

so for example: id 1, mean cost should be 20.

id,cost
1,10 
1,20
1,30
2,40
2,50

I got the output right with:

df.groupby(['id'])['cost'].mean()
id
1    20
2    45
Name: cost, dtype: int64

But i dont know how to plot such that x-axis is the id (1,2) and y axis as the mean values (20,45).

The below code made the mean to be the x-axis (should be on y-axis) while the y-axis is only until 1 (should be 2 and should be the x-axis).

df.groupby(['id'])['cost'].mean().hist()

enter image description here

like image 579
jxn Avatar asked Mar 06 '26 10:03

jxn


1 Answers

Piggybacking off of Psidom's comment...

df.groupby('id').mean().plot(kind='bar')

enter image description here


In [108]: df
Out[108]: 
   id  cost
0   1    10
1   1    20
2   1    30
3   2    40
4   2    50
like image 77
lanery Avatar answered Mar 08 '26 01:03

lanery



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!