简体   繁体   中英

Pandas groupby operations between groups

I have a DataFrame with 4 fields: Locatiom Year, Week and Sales. I would like to know the difference in Sales between two years preserving the granularity of the dataset. I mean, I would like to know for each Location, Year and Week, what is the difference to the same week of another Year.

The following will generate a Dataframe with a similar structure:

raw_data = {'Location': ['A']*30 + ['B']*30 + ['C']*30,
            'Year': 3*([2018]*10+[2019]*10+[2020]*10),
            'Week': 3*(3*list(range(1,11))),
            'Sales': random.randint(100, size=(90))
}
df = pd.DataFrame(raw_data)


Location    Year    Week    Sales
A   2018    1   67
A   2018    2   93
A   2018    …   67
A   2019    1   49
A   2019    2   38
A   2019    …   40
B   2018    1   18
…   …   …   …

Could you please show me what would be the best approach?

Thank you very much

You can do it using groupby and shift :

df["Next_Years_Sales"] = df.groupby(["Location", "Week"])["Sales"].shift(-1)
df["YoY_Sales_Difference"] = df["Next_Years_Sales"] - df["Sales"]

Spot checking it:

df[(df["Location"] == "A") & (df["Week"] == 1)]
Out[37]: 
   Location  Year  Week  Sales  Next_Years_Sales  YoY_Sales_Difference
0         A  2018     1     99              10.0                 -89.0
10        A  2019     1     10               3.0                  -7.0
20        A  2020     1      3               NaN                   NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM