我有一个与此非常相似的问题,但 1)我希望它也适用于系列,2)我没有代表我的分组值的列;值在索引中。
假设我有一个如下所示的系列:
2023-08-01 1515000.08
2023-09-01 2629410.80
2023-10-01 2548748.40
2023-11-01 2494398.04
2023-12-01 3397805.34
2024-01-01 3285501.49
2024-02-01 3173978.74
2024-03-01 3139235.65
2024-04-01 2927895.84
2024-05-01 2750708.29
dtype: float64
我想创建一个新系列,其中的值代表上一季度最后一个月的值,如下所示:
2023-08-01 NaN
2023-09-01 NaN
2023-10-01 2629410.80 <--- the old value from 2023-09-01, which was the end of Q3
2023-11-01 2629410.80
2023-12-01 2629410.80
2024-01-01 3397805.34 <--- the old value from 2023-12-01
2024-02-01 3397805.34
2024-03-01 3397805.34
2024-04-01 3139235.65 <--- the old value from 2024-03-01
2024-05-01 3139235.65
dtype: float64
我发现在这里找到一个优雅的解决方案非常麻烦。我的代码如下所示:
period_to_val = (
series.groupby(
lambda x: get_quarter(date=x)
)
.last()
.shift()
)
data = series.index.map(
lambda x: period_to_val[get_end_of_period(date=x, term_length=term_length, fiscal_year_start=fiscal_year_start)]
)
result = pd.Series(data=data, index=series.index)
但这感觉太冗长和丑陋了。我想要一个对 a和 aSeriesGroupBy
混合的操作,但这种东西似乎不存在。.shift()
.transform("last")
有什么改进建议吗?谢谢!