我有一个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
中的每一个c
,我想以百分比计算MoM
和YoY
的变化。这将是pct
,月列中的观测值和year
中的总百分比变化是不同的。
我正在寻找一个解决方案,它可以跨几个月列和几年进行推广。
预期产出:
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
差值。
发布于 2022-05-20 19:00:58
感谢您提供了如此好的示例输入。这里有一种方法,首先将表分解为长形式,然后通过遍历一个组来获得每个月的平均YoY,然后再通过另一个组来获得所有月份的平均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)
输出
https://stackoverflow.com/questions/72323192
复制相似问题