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

如何在Pandas中基于条件重置cummin()生成新列c?

问题描述

原始DataFrame

import pandas as pd 

df = pd.DataFrame(
    {
        'a': [98, 97, 100, 135, 103, 100, 105, 109, 130],
        'b': [100, 103, 101, 105, 110, 120, 101, 150, 160]
    }
)

期望输出

a    b    c
0   98  100  100
1   97  103  100
2  100  101  100
3  135  105  100
4  103  110  110
5  100  120  110
6  105  101  101
7  109  150  150
8  130  160  150

列c的生成逻辑

  • 初始时,列c取值为列b的累积最小值(df.b.cummin())
  • 当满足条件df.a.shift(1) > df.c.shift(1)(前一行的a值大于前一行的c值)时,当前行的c取对应行的b值,并从当前行开始重新计算b的累积最小值,重置累积计算起点。

尝试的无效代码

df['c'] = df.b.cummin()
df.loc[df.a.shift(1) > df.c.shift(1), 'c'] = df.b

有效解决方案

以下方案简洁高效,在大数据集也能稳定工作:

import pandas as pd

df = pd.DataFrame(
    {
        'a': [98, 97, 100, 135, 103, 100, 105, 109, 130],
        'b': [100, 103, 101, 105, 110, 120, 101, 150, 160]
    }
)

# 初始化c列和当前累积最小值
c = [df['b'].iloc[0]]
current_min = df['b'].iloc[0]

# 逐行计算c值
for i in range(1, len(df)):
    # 检查是否触发重置条件
    if df['a'].iloc[i-1] > c[i-1]:
        current_min = df['b'].iloc[i]
        c.append(current_min)
    else:
        current_min = min(current_min, df['b'].iloc[i])
        c.append(current_min)

df['c'] = c

方案说明

  • 从第一行开始,将b的第一个值作为初始累积最小值
  • 逐行判断前一行的a是否大于前一行的c:
    • 若满足条件,将当前行的b设为新的累积最小值,赋值给当前行的c
    • 若不满足条件,更新累积最小值为当前最小值与当前行b的较小值,赋值给当前行的c

补充说明

此前采用的向量化方案在示例数据集可正常运行,但在大规模数据集上未达预期。上述遍历方案逻辑清晰,能稳定处理各类数据场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:34:59