Home > Software design >  Pandas groupby index.month_name
Pandas groupby index.month_name

Time:05-19

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)

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.

CodePudding user response:

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()
  • Related