Pandas绘制来自相应唯一id值的平均值

时间:2016-10-16 00:53:29

标签: python pandas matplotlib plot

这是我的csv文件。我想找到每个唯一ID的平均成本。

所以例如:id 1,平均成本应该是20。

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

我的输出正确:

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

但我不知道如何绘制x轴是id(1,2)和y轴作为平均值(20,45)。

以下代码将平均值设为x轴(应位于y轴上),而y轴仅为1(应为2且应为x轴)。

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

enter image description here

1 个答案:

答案 0 :(得分:3)

背诵Psidom的评论......

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
相关问题