<p>您可以使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.expanding.html" rel="nofollow noreferrer">^{<cd1>}</a>方法获取之前所有值的中位数,并<code>shift</code>将结果与下一个YearMonth对齐,每个组使用<code>groupby</code>进行此操作</p>
<pre class="lang-py prettyprint-override"><code># get expanding median of the two columns and shift
median_prev = (
df.sort_values('YearMonth')
.groupby('Group')
[['PageViews','Users']]
.apply(lambda x: x.expanding().mean().shift())
)
print(median_prev.sort_index())
# PageViews Users
# 0 NaN NaN
# 1 100.0 10.0
# 2 NaN NaN
# 3 110.0 9.5
# 4 150.0 12.0
# 5 NaN NaN
</code></pre>
<p>然后,根据需要计算百分比差异。我想你想要:</p>
<pre class="lang-py prettyprint-override"><code># create the two columns, no need of sort_index,
# will do it automatically index and column alignment
df[[f'%change_{col}' for col in ['PageViews','Users']]] = \
((df[['PageViews','Users']]/median_prev-1)*100).round(1)
print(df)
Group YearMonth PageViews Users %change_PageViews %change_Users
0 A 202001 100 10 NaN NaN
1 A 202002 120 9 20.0 -10.0
2 B 202002 150 12 NaN NaN
3 A 202003 90 10 -18.2 5.3
4 B 202003 120 15 -20.0 25.0
5 C 202001 130 10 NaN NaN
</code></pre>