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

基于前后值为DataFrame中哑变量向量赋值的实现方法

解决DataFrame哑变量区间替换问题

这个需求本质是基于相邻非0值的区间标记替换,我们可以用Pandas结合简单的状态遍历思路来实现,逻辑清晰且容易验证。

步骤1:构造示例数据

首先我们先把你提供的原始数据转换成Pandas Series(如果是DataFrame的列,直接提取对应列即可):

import pandas as pd
import numpy as np

# 你的原始数据
raw_data = [2,2,0,0,0,0,1,1,1,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,2]
s = pd.Series(raw_data)

步骤2:标记区间状态

我们需要先找到所有非0值的位置(这些是我们的"锚点"),然后遍历相邻锚点之间的区间,根据锚点值判断该区间的0应该替换成3还是4:

# 初始化状态数组,用来存储每个位置的替换值(0表示不需要替换)
state = np.zeros(len(s), dtype=int)

# 提取所有非0值的索引和对应值,重置索引方便遍历
non_zero_points = s[s != 0].reset_index()

# 遍历每一对相邻的非0锚点
for i in range(len(non_zero_points) - 1):
    # 获取当前锚点的结束位置、下一个锚点的起始位置
    start_idx = non_zero_points.iloc[i]['index'] + 1
    end_idx = non_zero_points.iloc[i+1]['index']
    current_val = non_zero_points.iloc[i][0]
    next_val = non_zero_points.iloc[i+1][0]
    
    # 规则1:2之后、1之前的0 → 替换为3
    if current_val == 2 and next_val == 1:
        state[start_idx:end_idx] = 3
    # 规则2:1之后、2之前的0 → 替换为4
    elif current_val == 1 and next_val == 2:
        state[start_idx:end_idx] = 4

步骤3:完成替换

最后用where方法保留原始非0值,把0替换为对应的状态值:

result = s.where(s != 0, state)

# 输出结果验证
print(result.tolist())

运行后得到的结果就是你想要的目标序列:

2 2 3 3 3 3 1 1 1 4 4 4 4 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 4 4 4 4 4 4 4 4 2 2 2 3 3 3 3 3 3 3 3 3 3 1 1 1 4 4 4 4 4 4 2

这个方法的优势是逻辑直观,完全匹配你的规则,而且容易扩展——如果以后有新的区间替换规则,只需要在遍历的时候加对应的条件判断即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:13:13