计算平均Yoy百分比变化-pandas DataFrame
我有一个带有每月观察结果的熊猫数据框架。我想计算几个指标 - 妈妈和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
更改百分比。这将是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
计算为百分比
年度所有月度值的总和之间的差异。
I have a Pandas DataFrame with Monthly observations. I'd like to calculate a couple of metrics - MoM and YoY pct change.
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]
})
For each z
in c
, I'd like to calculate the MoM
and YoY
change in percentage. This is would be pct
different between observations in month column and aggregate percent change in year
.
I am looking for a solution that is generalizable across several monthly columns and year.
Expected output:
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
is calculated as percentage
difference between sum of all monthly values of the year.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您很好地提供示例输入。这是一种首先将桌子融化为长形式的方法,然后终止一个集体比以每月的平均年龄,然后在所有月份获得平均年龄。我认为,更多的月和几年列
输出
Thanks for providing example input so nicely. Here's an approach that first melts the table into long form and then permforms a groupby to get average YoY for each month, and then another groupby to get average YoY over all months. I think it is flexible to more months and years columns
Output