python - 如何使用 pd.shift 获取值
问题描述
我试图通过从上一行motooutstandingbalance
中减去上一行来填充列中的值。我正在使用 pandas shift 命令,但目前没有得到所需的输出,这应该是每周持续减少。actualmotordeductionfortheweek
motooutstandingbalance
motooutstandingbalance
这是我的代码
x['motooutstandingbalance']=np.where(x.salesrepid == x.shift(1).salesrepid, x.shift(1).motooutstandingbalance - x.shift(1).actualmotordeductionfortheweek, x.motooutstandingbalance)
关于如何实现这一目标的任何想法?
解决方案
这有效:
start_value = 468300.0
df['motooutstandingbalance'] = (-df['actualmotordeductionfortheweek'][::-1]).append(pd.Series([start_value], index=[-1]))[::-1].cumsum().reset_index(drop=True)
基本上我正在做的是我——</p>
- 取
actualmotordeductionfortheweek
列,否定它(所有值都变为负数),然后反转它 - 在索引处添加起始值(它是正值,而不是所有其他负值)
-1
(它是 before0
,而不是像 Python 中通常那样在最后) - 将其反转,以便新
-1
条目从头开始 - 用于
cumsum()
添加列的所有值。这实际上可以从起始值中减去所有值,因为第一个值为正,其余值为负(因为x + (-y) = x - y
)
推荐阅读
- c# - 将类型“System.Data.DataSet”转换为“字符串”错误
- javascript - 如何对齐4个圆圈
- oop - 如何在我的代码中防止“仅调用其他方法的方法”?
- svelte - 如何调用 svelte:component 当前组件方法?
- linux - 如果语句在 bash 脚本中接受是或否?
- python - Django Test DoesNotExist:在模型中测试函数时出现“匹配查询不存在”错误
- html - GET http://localhost:3000/public/frontpage.png 404(未找到)(图片)
- c - Unicode 符号
- reactjs - 如何让 React.memo 功能与孩子一起工作?
- maya - Does anyone know why an asset would appear invisible when imported into a scene in Maya?