Search code examples
pythonpandasdataframegroup-by

How to groupby in pandas for multiple periods (season and weekday)?


I have a dataframe containing ~3 years of data looking something like this:

enter image description here

I can groupby the whole dataframe by weekdays, to get the average value for each of them, by doing

df_weekday = df.groupby(df.index.weekday).mean()

But I want to have not just the average value for each weekday, but have this for every season within my dataframe of ~3 years - meaning, average value for Mon to Sun for winter, average value for Mon to Sun for spring and so on.

How can I do this? Tnx


Solution

  • You can group by more than 1 columns:

    # Use whatever logic to determine your season. Here, I simply assign each
    # quarter (92 days) to a season
    season = (df.index.day_of_year // 92).map({
        0: "Winter",
        1: "Spring",
        2: "Summer",
        3: "Fall"
    })
    df.groupby([season, df.index.weekday]).mean()