我有以下数据集:
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_cost 时 actual_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/