首页 > 解决方案 > 如何使用 pd.shift 获取值

问题描述

在此处输入图像描述

我试图通过从上一行motooutstandingbalance中减去上一行来填充列中的值。我正在使用 pandas shift 命令,但目前没有得到所需的输出,这应该是每周持续减少。actualmotordeductionfortheweekmotooutstandingbalancemotooutstandingbalance

最终结果应该是这样的 在此处输入图像描述

这是我的代码

x['motooutstandingbalance']=np.where(x.salesrepid == x.shift(1).salesrepid, x.shift(1).motooutstandingbalance - x.shift(1).actualmotordeductionfortheweek, x.motooutstandingbalance)

关于如何实现这一目标的任何想法?

标签: pythonpandasnumpy

解决方案


这有效:

start_value = 468300.0
df['motooutstandingbalance'] = (-df['actualmotordeductionfortheweek'][::-1]).append(pd.Series([start_value], index=[-1]))[::-1].cumsum().reset_index(drop=True)

基本上我正在做的是我——</p>

  1. actualmotordeductionfortheweek列,否定它(所有值都变为负数),然后反转它
  2. 在索引处添加起始值(它是正值,而不是所有其他负值)-1(它是 before 0,而不是像 Python 中通常那样在最后)
  3. 将其反转,以便新-1条目从头开始
  4. 用于cumsum()添加列的所有值。这实际上可以从起始值中减去所有值,因为第一个值为正,其余值为(因为x + (-y) = x - y

推荐阅读