Pandas - 聚合和绘制结果

Pandas - Aggregating and Plotting Results

我有一个我认为应该相当简单的问题,但我已经与它抗争了几个小时

我想对 pandas 数据框进行聚合,然后使用 matplotlib

绘制它

我从大量 table 年的汽车型号开始。然后我想计算总销售价格和要价的百分比。

我这样做如下

percent_asking_price =(df.groupby(['year','model'])['salesprice'].sum()/df.groupby(['year','model'])['askingprice'].sum())*100

这似乎做了我想让它做的事,但我不知道如何处理输出 - returns 输出看起来像:

从那时起,我不知道该如何处理它。我想使用 matplotlib 绘制年份和型号名称的组合,使其看起来像这样:

有点沮丧,因为这是我可以在 r 中使用 ddply 和 ggplot 非常快速地完成的事情,但在这里无法取得任何进展

我已经尝试将输出转换为数据帧,但这并没有帮助我

非常感谢帮助

将显示结果的小集合如下:

year,model,salesprice,askingprice
2009,Taurus,25410,30000
2009,Taurus,8698,10000
2009,Maxima,11135,15000
2009,Maxima,8500,10000
2010,Corvette,25000,30000
2010,Corvette,18320,20000
2010,Trans Am,32000,35000
2010,Trans Am,23620,25000

最后 - 有没有办法将输出转换为如下所示的数据帧,以便我可以对输出做进一步的工作?我不想丢失第一列中的值..

谢谢!

试试这个:

In [383]: df_plt = ((df.groupby(['year','model'])['salesprice'].sum() \
   .....:            / \
   .....:            df.groupby(['year','model'])['askingprice'].sum())*100).reset_index()

In [384]: df_plt
Out[384]:
   year     model      0
0  2009    Maxima  78.54
1  2009    Taurus  85.27
2  2010  Corvette  86.64
3  2010  Trans Am  92.70

In [385]: df_plt['Year_Model'] = df_plt.year.astype(str) + ' ' + df_plt.model

In [386]: df_plt
Out[386]:
   year     model      0     Year_Model
0  2009    Maxima  78.54    2009 Maxima
1  2009    Taurus  85.27    2009 Taurus
2  2010  Corvette  86.64  2010 Corvette
3  2010  Trans Am  92.70  2010 Trans Am


In [387]: df_plt = df_plt.set_index('Year_Model')[[0]].rename(columns={0:'Percent Asking Price'})

In [388]: df_plt
Out[388]:
               Percent Asking Price
Year_Model
2009 Maxima                   78.54
2009 Taurus                   85.27
2010 Corvette                 86.64
2010 Trans Am                 92.70

In [389]: matplotlib.style.use('ggplot')

In [390]: ax = df_plt.plot(kind='bar', rot=0)

In [391]: ax.yaxis.grid(True)