首页 > 解决方案 > 计算每个集群的时间序列数据的季节性和趋势

问题描述

我有这个时间序列数据,现在我想使用“ modal_price ”计算每个 APMC 和商品集群的趋势季节性类型(乘法或加法)。数据集有大约 60,000 行这样的行,其中 APMC 和 Cluster 相同,但日期在变化。数据集如下:

             APMC |   Commodity  | qtl _weight| min_price | max_price | modal_price | district_name | Year | Month
date
2014-12-01  Akole   bajri            40              1375        1750      1563          Ahmadnagar  2014   12
2014-12-01  Akole   paddy-unhusked   346             1400        1800      1625          Ahmadnagar  2014   12
2014-12-01  Akole   wheat            55              1500        1900       1675         Ahmadnagar  2014   12
2014-12-01  Akole   bhagar/vari      59              2000        2600       2400         Ahmadnagar  2014   12
2014-12-01  Akole   gram              9              3200        3300       3235         Ahmadnagar  2014   12
2014-12-01  Jamkhed cotton           44199           3950        4033       3991         Ahmadnagar  2014   12
2014-12-01  Jamkhed bajri            846             1300        1488       1394         Ahmadnagar  2014   12
2014-12-01  Jamkhed wheat(husked)    155             1879        2231       2055         Ahmadnagar  2014   12
2014-12-01  Kopar   gram             421             1983        2698       2463         Ahmadnagar  2014   12
2014-12-01  Kopar   greengram         18             6734        7259       6759         Ahmadnagar  2014   12
2014-12-01  Kopar   soybean          1507            2945        3247       3199         Ahmadnagar  2014   12
2016-11-01  Sanga   wheat(husked)    222             1730        2173       1994         Ahmadnagar  2016   11

现在我尝试使用(APMC,商品和日期作为索引)为此数据透视表,但这无助于计算每个集群(APMC,商品)的平均值(计算趋势)。我只需要知道如何使用 'modal_price' 计算每个集群(APMC,Commodity)的平均值,并将其添加为 dataframe/pivot-table 中的 COLUMN。

标签: pythonpandasgroup-bytime-seriespivot-table

解决方案


也许 groupby 会给你趋势所需的东西,然后 transform 会让你能够将它投影回相同的索引上?就像是:

# group by your cluster
g = df.groupby(["Year", "APMC", "Commodity"])
# determine the trend per cluster but finalise back into original diimensions
trend = g.modal_price.transform(lambda x: x.mean())
df["trend"] = trend

推荐阅读