python - pandas 数据框中的值之间的比较

标签 python pandas

我有一个 df 作为

enter image description here

我想过滤出同比变化百分比和不同季度之间的总变化。

enter image description here

我不确定如何在 python 中启动它,任何帮助将不胜感激。

考虑到我有很多名称参数。我需要对每个 KPI、年份和季度使​​用分组筛选器,我尝试过

d2['d'] = d2.groupby(['KPI', 'Quarter', ])['Number'].apply( lambda x: (x - x.shift(4))/x  )

最佳答案

使用Series,pct_change每组,乘以 mul如有必要round :

d2['Percent Change'] = (d2.groupby(['KPI', 'Quarter'])['Number']
                          .transform(pd.Series.pct_change)
                          .mul(100)
                          .round())

对于总更改,请添加 cumsum

d2['Total Change'] = d2['Number'].pct_change().cumsum().mul(100).round().fillna(0)

关于python - pandas 数据框中的值之间的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53810655/

相关文章:

python - 将 Pandas 数据框中的值从字符串映射到 int(例如使用 Gender)

python - Pyspark RDD : find index of an element

python - python 查找两个标签之间的所有内容

python - 使用 Python 查找电子邮件正文中的链接

python - odoo 导入 .xlsx 销售订单、购买订单

python-3.x - key 错误 : "None of [Int64Index([1960, 1961, 1962, 1963, 1964], dtype=' int6 4')] are in the [columns]"

python - Python 是用来做什么的?

python - 如何在 python 中处理缺失的 NaN 以进行机器学习

python-3.x - 如何将Excel负值转换为Pandas负值

python - 如何从时间戳中分割日期并转换为字符串?