python - 当当前列最后一个非零时获取另一列的值(Pandas 数据帧)

标签 python pandas

我有一个与此类似的数据框,其中包含枚举日期、ID 以及给定日期和 ID 内销售的商品数量:

Date  ID  num_sold
0     1   0
      2   13
1     1   6
      2   0
2     1   0
      2   0
3     1   5
      2   4

对于每个 ID,我想计算上次销售发生的日期。所以我有以下数据框:

Date  ID  num_sold  last_sale
0     1   0         -1
      2   13        -1
1     1   6         -1
      2   0         0
2     1   0         1
      2   0         0
3     1   5         1
      2   4         0

我想计算last_sale列,其中1和0是给定ID时的日期值,num_sold是最后一个非-零。如果没有这样的最后日期(例如数据集中的第一个月),则它是 -1 (或者可能是 nan)。

在给定的示例中,

在日期 1,ID 1 以前从未售出过,因此我们将 last_sale 设置为 -1。 ID 2 最后一次销售是在第 0 个月,因此我们将 last_sale 设置为 0。

同样,在日期 3,ID 1 最后一次销售是在第 1 个月,因此 last_sale 为 1,而 ID 2 最后一次销售是在第 0 个月,因此 last_sale 为 0 .

完成此任务最有效、最简洁的方法是什么?

最佳答案

首先,为当前销售日期创建一列:

df["current_sale_date"] = 0
df.loc[df.num_sold != 0, "current_sale_date"] = df.Date

您为上次销售日期创建另一列。首先,将 0 替换为 np.nan 以允许 .ffill() 工作。然后,对于每个 ID,您可以通过 .fill() 获得当前销售日期的值。

df.current_sale_date = df.current_sale_date.replace(0, np.nan)    
df["last_sale_date"] = df.groupby(['ID'])['current_sale_date'].ffill()

然后您可以通过 ID 获取之前的销售日期和类次

 df.last_sale_date = df.groupby(['ID'])['last_sale_date'].shift()

对于第一次日期,您设置 -1

df.loc[df.Date == df.Date.idxmin(), "last_sale_date"] = -1

您将 nan 替换为 0,因为 0 是日期

df.last_sale_date = df.last_sale_date.replace(np.nan, 0)

首次出售 ID 时,如果没有之前的出售日期,则设置 -1

 df.loc[(df.current_sale_date == 1) & (df.last_sale_date == 0), "last_sale_date"] = -1

关于python - 当当前列最后一个非零时获取另一列的值(Pandas 数据帧),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51881618/

相关文章:

python - 使用 sklearn StandardScaler 缩放的数据平均值不为零

python - 截断数据框中的所有值

python - 将概率分布拟合到数据并找到它的累积分布函数

python - 删除两个列表中具有相同元素的元组

python - 应该定义密集层输入的最后一个维度。没有发现。收到完整的输入形状 : <unknown>

python - 类型错误 : pivot_table() got multiple values for keyword argument 'values'

python - 按组重新索引 Pandas 时间序列

python - 将 Band 对象添加到 Bokeh 中的图例?

python - Power BI 中 Python 可视化中时间序列的最佳数据格式是什么?

python - 累积 pandas 数据框/时间序列中的进入和退出