python - 获取百分比变化,其中轴等于 python pandas 中的列?

标签 python python-3.x pandas group-by

我有以下数据集:

import pandas as pd
w = pd.Series(['EY', 'EY', 'EY', 'KPMG', 'KPMG', 'KPMG', 'BAIN', 'BAIN', 'BAIN'])
x = pd.Series([2020,2019,2018,2020,2019,2018,2020,2019,2018])
y = pd.Series([100000, 500000, 1000000, 50000, 100000, 40000, 1000, 500, 4000])
z = pd.Series([10000, 10000, 20000, 25000, 50000, 10000, 100000, 50500, 120000])
df = pd.DataFrame({'consultant': w, 'fiscal_year':x, 'actual_cost':y, 'budgeted_cost':z})

indexer_consultant_fy = ['consultant', 'fiscal_year']
df = df.set_index(indexer_consultant_fy).sort_index(ascending=True)
df['actual_budget_pct_diff'] = df.pct_change(axis='columns',fill_method='ffill')['budgeted_cost']

如何让 actual_cost 和 budgeted_cost 在最后一行代码中切换而不切换数据框中的列?

结果应该是当 actual_cost 高于 budgeted_costactual_budget_pct_diff 将是一个正数?谢谢大家!

最佳答案

只需指定 periods=-1 并选择列 [actual_cost],如下所示:

df['actual_budget_pct_diff'] = df.pct_change(periods=-1, axis='columns',fill_method='ffill')['actual_cost']

Out[160]:
                        actual_cost  budgeted_cost  actual_budget_pct_diff
consultant fiscal_year
BAIN       2018                4000         120000               -0.966667
           2019                 500          50500               -0.990099
           2020                1000         100000               -0.990000
EY         2018             1000000          20000               49.000000
           2019              500000          10000               49.000000
           2020              100000          10000                9.000000
KPMG       2018               40000          10000                3.000000
           2019              100000          50000                1.000000
           2020               50000          25000                1.000000

关于python - 获取百分比变化,其中轴等于 python pandas 中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56863136/

相关文章:

string - 删除具有特定字符串值 pandas 的行

python - 自定义 django runserver 输出

python - 如何循环所有图像像素并判断它们是黑色还是白色

python - 跨不同平台的python中errno模块的可用性

python - Exif阅读库

python - pandas 数据框,将 index_col 设置为我的 csv 名称

python - 绘制数据框的热图

python - 为什么在尝试设置 virtualenv 时出现此错误(与 pip 和 easy_install 相关)?

Python 你为什么要使用 [ :] over =

python - 将系列索引设置为另一个具有更多级别的索引