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

如何用Pandas布尔索引筛选符合三类条件的时间序列数据?

问题与解决方案

给定时间序列

[0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0]

布尔索引要求

  • 包含2以及2之后的元素
  • 元素值大于0
  • 遇到0时终止

期望输出布尔向量

[False, False, True, True, True, True, False, False, True, True, True, True, False]

尝试的未成功代码

frame['boolean'] = False
frame['boolean'].loc[(frame['sequence'].gt(2)) & (frame['boolean'].shift(1).eq(False)] = True

可行解决方案

方法一:状态机遍历(简洁高效)

直接遍历序列,通过状态变量跟踪是否处于需要标记的区间:

import pandas as pd

# 构造数据
sequence = [0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0]
frame = pd.DataFrame({'sequence': sequence})

active = False
boolean_result = []
for num in sequence:
    # 遇到2时激活标记状态
    if num == 2:
        active = True
    # 遇到0时终止标记状态
    if num == 0:
        active = False
    # 只有激活状态且数值>0时标记为True
    boolean_result.append(active and num > 0)

frame['boolean'] = boolean_result
print(frame['boolean'].tolist())

方法二:区间标记法

先定位所有起点(值为2的位置)和终点(值为0的位置),再逐个区间设置标记:

import pandas as pd

sequence = [0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0]
frame = pd.DataFrame({'sequence': sequence})
frame['boolean'] = False

# 获取所有起点和终点的索引
start_indices = frame[frame['sequence'] == 2].index
end_indices = frame[frame['sequence'] == 0].index

# 遍历每个起点,找到对应的下一个终点
for start in start_indices:
    # 找到当前起点之后的第一个终点
    next_end = end_indices[end_indices > start].min()
    # 对区间内符合条件的位置设为True
    mask = frame.loc[start:next_end-1, 'sequence'] > 0
    frame.loc[start:next_end-1, 'boolean'] = mask

print(frame['boolean'].tolist())

两种方法都能输出你期望的布尔向量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:10:39