You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Pandas中实现Excel MAXIFS功能:按ID求后续最大值

问题描述

我尝试使用Pandas创建一个新列,填充每个id对应的后续最高值。

以下是输入数据和期望得到的结果。

我研究过where/groupby/transform方法,但它无法满足我的需求,因为我需要基于每行的where条件,而非常量值。

注:这等价于Excel公式MAXIFS(C:C;A:A;A2;B:B;">"&B2),其中:A = id;B = date;C = value

输入数据

import pandas as pd
from datetime import datetime

df = pd.DataFrame({
    "id": ["a"] * 2 + ["b"] * 4 + ["a", "b"] * 2 + ["b"],
    "date": pd.date_range(datetime(2023, 1, 1), periods=11).tolist(),
    "value": [3, 10, 2, 20, 24, 9, 21, 7, 25, 12, 7]
})

#    id       date  value
# 0   a 2023-01-01      3
# 1   a 2023-01-02     10
# 2   b 2023-01-03      2
# 3   b 2023-01-04     20
# 4   b 2023-01-05     24
# 5   b 2023-01-06      9
# 6   a 2023-01-07     21
# 7   b 2023-01-08      7
# 8   a 2023-01-09     25
# 9   b 2023-01-10     12
# 10  b 2023-01-11      7
期望输出
import pandas as pd
import numpy as np
from datetime import datetime

df_expected = pd.concat(
    [df, pd.DataFrame({
        "next_local_max": [25, 25, 24, 24, 12, 12, 25, 12, np.nan, 7, np.nan]
    })],
    axis=1
)

#    id       date  value  next_local_max
# 0   a 2023-01-01      3            25.0
# 1   a 2023-01-02     10            25.0
# 2   b 2023-01-03      2            24.0
# 3   b 2023-01-04     20            24.0
# 4   b 2023-01-05     24            12.0
# 5   b 2023-01-06      9            12.0
# 6   a 2023-01-07     21            25.0
# 7   b 2023-01-08      7            12.0
# 8   a 2023-01-09     25             NaN
# 9   b 2023-01-10     12             7.0
# 10  b 2023-01-11      7             NaN
补充说明

本问题已得到妥善解答。我尝试进一步扩展该问题,以应对更复杂的最大值条件需求。


内容的提问来源于stack exchange,提问作者Alexandre_K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:24:52