python - Plotting pandas groupby -


i have dataframe car data - structure pretty simple. have id, year of production, kilometers, price , fuel type (petrol/diesel).

in [106]: stack.head()  out[106]:     year    km      price   fuel 0   2003    165.286 2.350   petrol 1   2005    195.678 3.350   diesel 2   2002    125.262 2.450   petrol 3   2002    161.000 1.999   petrol 4   2002    164.851 2.599   diesel 

i trying produce chart pylab/matplotlib x-axis year , then, using groupby, have 2 plots (one each fuel type) averages year (mean function) price , km.

any appreciated.

maybe there's more straight way it, following. first groupby , take means price:

meanprice = df.groupby(['year','fuel'])['price'].mean().reset_index() 

and km:

meankm = df.groupby(['year','fuel'])['km'].mean().reset_index() 

then merge 2 resulting dataframes data in one:

d = pd.merge(meanprice,meankm,on=['year','fuel']).set_index('year') 

setting index year ley things easy while plotting pandas. resulting dataframe is:

        fuel   price       km year                          2002  diesel  2.5990  164.851 2002  petrol  2.2245  143.131 2003  petrol  2.3500  165.286 2005  diesel  3.3500  195.678 

at end can plot filtering fuel:

d[d['fuel']=='diesel'].plot(kind='bar')  d[d['fuel']=='petrol'].plot(kind='bar') 

obtaining like:

enter image description here

enter image description here

i don't know if kind of plot expected, can modify them kind keyword. hope helps.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -