Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas groupby index.month_name

Code

def plot_data_by_month(data, x, y) :
    data_by_month = data[data[y] > 0].groupby(data[data[y] > 0].index.month_name())[y].mean()

    ax = data_by_month.plot(figsize=(15, 10))
    ax.set_title(y + ' ' + 'by Month of Year')
    ax.set_xlabel('Month')
    ax.set_ylabel(y)
    time_labels = data_by_month.index
    ticks = ax.set_xticks(range(len(time_labels)), time_labels)

plot_data_by_month(chiller1, 'Time', 'kWE')

Outcome

Picture of graph (Can’t imbed photos yet)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Not sure how to get the months out of alphabetical order and into calender order, the data frame is order from oldest – newest (Jan – Dec) so not sure how to fix the issue.

>Solution :

You can filter rows only once to helper DataFrame df1, if necessary sorting DatetimeIndex and for prevent sorting add sort=False to groupby:

df1 = data[data[y] > 0].sort_index()
data_by_month = df1.groupby(df1.index.month_name(), sort=False)[y].mean()

instead:

data_by_month = data[data[y] > 0].groupby(data[data[y] > 0].index.month_name())[y].mean()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading