Skip to content Skip to sidebar Skip to footer

Plot The Result Of A Groupby Operation In Pandas

I have this sample table: ID Date Days Volume/Day 0 111 2016-01-01 20 50 1 111 2016-02-01 25 40 2 111 2016-03-01 31 35 3 111 2016-04-01 30 30 4 111 201

Solution 1:

Get a groupby object.

g = df.groupby('ID')

Compute columns with transform:

df['CumDays']=g.Days.transform('cumsum')df['FirstVolume/Day']=g['Volume/Day'].transform('first')dfIDDateDaysVolume/DayCumDaysFirstVolume/Day01112016-01-01    2050205011112016-02-01    2540455021112016-03-01    3135765031112016-04-01    30301065041112016-05-01    31251375051112016-06-01    30201675061112016-07-01    31201985071112016-08-01    31152295081112016-09-01    29152585091112016-10-01    311028950101112016-11-01    29531850111112016-12-01    2703455001122016-01-01    3155315511122016-01-02    2645575521122016-01-03    3140885531122016-01-04    30351185541122016-01-05    31301495551122016-01-06    30251795561122016-01-07    31252105571122016-01-08    31202415581122016-01-09    30202715591122016-01-10    311530255101122016-01-11    291033155111122016-01-12    31036255

If you want grouped plots, you can iterate over each groups after grouping by ID. To plot, first set index and call plot.

fig, ax = plt.subplots(figsize=(8,6))
for i, g in df2.groupby('ID'):
    g.plot(x='CumDays', y='Volume/Day', ax=ax, label=str(i))

plt.show()

enter image description here

Post a Comment for "Plot The Result Of A Groupby Operation In Pandas"