[英]Calculate mean YoY percentage change - Pandas DataFrame
我有一個每月觀察的 Pandas DataFrame。 我想計算幾個指標——MoM 和 YoY pct 變化。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'c': ['A','A','A','B','B','B','C','C'],
'z': [1, 2, 3, 4, 5, 6, 7, 8],
'2018-01': [10, 12, 14, 16, 18, 20, 22, 24],
'2018-02': [12, 14, 16, 18, 20, 22, 24, 26],
'2019-01': [8, 10, 12, 14, 16, 18, 20, 22],
'2019-02': [10, 12, 14, 16, 18, 20, 22, 24]
})
對於c
中的每個z
,我想計算MoM
和YoY
的百分比變化。 這在月份列中的觀察值和year
中的聚合百分比變化之間會有pct
不同。
我正在尋找一種可在多個月度專欄和年份中推廣的解決方案。
預期輸出:
c z 2018-01 2018-02 2019-01 2019-02 Avg_YoY_pct
A 1 10 -18.18
A 2 12
A 3 14
B 4 .............................
B 5
B 6
C 7
C 8
Avg_YoY_pct
計算為當年所有月度值總和之間的percentage
差異。
感謝您提供如此好的示例輸入。 這是一種方法,首先將表格融合為長格式,然后執行 groupby 以獲得每個月的平均 YoY,然后另一個 groupby 獲得所有月份的平均 YoY。 我認為它對更多月份和年份的專欄很靈活
#melt the wide table into a long table
long_df = df.melt(
id_vars=['c','z'],
var_name='date',
value_name='val',
)
#extract the year and month from the date column
long_df[['year','month']] = long_df['date'].str.split('-', expand=True)
long_df['year'] = long_df['year'].astype(int)
long_df['month'] = long_df['month'].astype(int)
#group by c/z/month and shift to get avg yoy for each month
avg_month_yoy = long_df.groupby(['c','z','month'])['val'].apply(
lambda v: v.sub(v.shift(1)).div(v.shift(1)).multiply(100).mean()
).reset_index()
#group by just c/z to get avg yoy over all months
avg_yoy = avg_month_yoy.groupby(['c','z'])['val'].mean()
#Add the avg_yoy back into the original table
df = df.set_index(['c','z'])
df['Avg_YoY_pct'] = avg_yoy
df = df.reset_index()
print(df)
輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.