首页 > 解决方案 > 如何使用 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()

找到具有最大库存计数的行。

但是,这给了我原始数据框的行标签。所以我不知道从哪里开始,因为我的计划是从最大库存数量的行中获取日期,然后忽略之前的任何日期。

标签: pythonpandas

解决方案


你仍然可以使用idxmaxbut 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

推荐阅读