繁体   English   中英

Pandas groupby 组间操作

[英]Pandas groupby operations between groups

我有一个包含 4 个字段的 DataFrame:Locatiom Year、Week 和 Sales。 我想知道保留数据集粒度的两年间销售额的差异。 我的意思是,我想知道对于每个地点、年份和周,与另一年的同一周有什么区别。

以下将生成具有类似结构的 Dataframe:

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
…   …   …   …

你能告诉我什么是最好的方法吗?

非常感谢

您可以使用groupbyshift来做到这一点:

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

抽查一下:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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