python - 如何使用 pandas 计算库存何时用完?
问题描述
假设我有一个像这样的 DataFrame:
Item Check Date Inventory
Apple 1/1/2020 50
Banana 1/1/2020 80
Apple 1/2/2020 75
Banana 1/2/2020 300
Apple 2/1/2020 100
Apple 2/2/2020 98
Banana 2/2/2020 341
Apple 2/3/2020 95
Banana 2/3/2020 328
Apple 2/4/2020 90
Apple 2/5/2020 85
Banana 2/5/2020 325
我想从最大库存计数开始找到给定项目的平均库存变化率,然后用它来计算库存将在哪一天达到零。所以对于苹果来说,它会从 2/1:2+3+5+5/4 = 3.75
开始,香蕉也是从 2/2 开始13+3/2 = 8
。
由于有不同的项目,我使用过:
apples = df[df["Item"] == "apples"]
只为苹果获取数据框,然后使用:
apples["Inventory"].idxmax()
找到具有最大库存计数的行。
但是,这给了我原始数据框的行标签。所以我不知道从哪里开始,因为我的计划是从最大库存数量的行中获取日期,然后忽略之前的任何日期。
解决方案
你仍然可以使用idxmax
but withtransform
s=df[df.index>=df.groupby('Item').Inventory.transform('idxmax')]
out=s.groupby('Item')['Inventory'].apply(lambda x : -x.diff().mean())
Item
Apple 3.75
Banana 8.00
Name: Inventory, dtype: float64
推荐阅读
- c# - 我需要将 C# 代码上的 Razor 块翻译成 VB.NET
- r - 创建新的重复索引,其中每个数字的范围尽可能有效地依赖于另一列的索引
- node.js - 让 Docker 与 Gulp 和 Browsersync 一起工作
- g++ - g++ 错误:无法使用 -fsanitize=address 指定 -static
- javascript - Angularjs $HTTP POST JSON 数据到服务器问题
- node.js - 在 node.js 中作为子进程运行 shell(bash, zsh, sh...)
- reactjs - 用户使用浏览器后退按钮后如何恢复我的应用程序的先前状态?
- google-apps-script - 活动结束日期不正确
- javascript - 在 gulp.series 中传递函数参数
- azure-devops - 将项目上传到 Azure Devops