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

Pandas按条件新增列:指定周期内最大值对应行标记布尔值

问题描述

现有如下两列的Pandas DataFrame:

value  boolean
0        1        0
1        5        1
2        0        0
3        3        0
4        9        1
5       12        0
6        4        0
7        7        1
8        8        1
9        2        0
10      17        0
11      15        1
12       6        0

需要新增new_boolean列,生成规则如下(示例中指定周期period=4):

  • 首先筛选所有boolean == 1的行
  • 对每个符合条件的行,取其往前共period长度范围内的所有行(不足period行则从表头开始取)
  • 将该范围内value列最大值对应的行的new_boolean设为1,其余为0

规则示例:

  1. 行索引为1的位置boolean==1,往前取period=4行对应的value为[1,5],最大值为5,因此该行的new_boolean设为1
  2. 行索引为7的位置boolean==1,往前取period=4行对应的value为[9,12,4,7],最大值为12,因此value=12所在的索引5行的new_boolean设为1

预期输出

value  boolean  new_boolean
0        1        0            0
1        5        1            1
2        0        0            0
3        3        0            0
4        9        1            1
5       12        0            1
6        4        0            0
7        7        1            0
8        8        1            0
9        2        0            0
10      17        0            1
11      15        1            0
12       6        0            0

结果示意图:
结果示意图

实现代码

import pandas as pd

# 构造示例DataFrame
data = {
    'value': [1,5,0,3,9,12,4,7,8,2,17,15,6],
    'boolean': [0,1,0,0,1,0,0,1,1,0,0,1,0]
}
df = pd.DataFrame(data)
period = 4

# 初始化new_boolean列全为0
df['new_boolean'] = 0

# 遍历所有boolean为1的行索引
for idx in df[df['boolean'] == 1].index:
    # 计算窗口左边界,避免小于0
    left_bound = max(0, idx - period + 1)
    # 提取窗口内的value列
    window_value = df.loc[left_bound:idx, 'value']
    # 找到窗口内最大值对应的行索引
    max_value_idx = window_value.idxmax()
    # 对应位置标记为1
    df.loc[max_value_idx, 'new_boolean'] = 1

# 输出结果
print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:18:00