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

调整Pandas DataFrame以训练事件提前预测回归模型

数据处理需求与现有方法问题

我的DataFrame包含多个预测变量列(如示例中的B、C)和一个目标事件列A,A的取值为1(事件发生)或0(事件未发生),原数据中可能存在连续时间戳对应的A值为1的情况。

我需要实现以下处理逻辑:

  • 当事件发生(A=1)时,将事件标记向后偏移m行(由shift_by参数控制)
  • 删除从原事件发生行到偏移后行之间的所有行(包含原事件行)
  • 最终要让ML模型提前看到事件标记,同时无法获取事件发生前后shift_by行的原始预测变量数据,且尽量保留原数据的事件发生模式

目前我使用了适用于分类问题的curve_shift方法处理偏移,后续用delete_duplicate_ones方法删除连续重复的1,但这两个方法无法满足需求:delete_duplicate_ones会删除所有连续重复的1,无论这些1来自原数据还是偏移操作。


示例DataFrame

import pandas as pd
df = pd.DataFrame({
    'A': [0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0],
    'B': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
    'C': [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]
})

现有方法代码

curve_shift方法(实现偏移)

sign = lambda x: (1, -1)[x < 0]
def curve_shift(df, shift_by):
    vector = df['A'].copy()
    for s in range(abs(shift_by)):
        tmp = vector.shift(sign(shift_by))
        tmp = tmp.fillna(0)
        vector += tmp
    labelcol = 'A'
    # Add vector to the df
    df.insert(loc=0, column=labelcol+'tmp', value=vector)
    # Remove the rows with labelcol == 1.
    df = df.drop(df[df[labelcol] == 1].index)
    # Drop labelcol and rename the tmp col as labelcol
    df = df.drop(labelcol, axis=1)
    df = df.rename(columns={labelcol+'tmp': labelcol})
    # Make the labelcol binary
    df.loc[df[labelcol] > 0, labelcol] = 1
    return df

delete_duplicate_ones方法(删除连续重复1)

def delete_duplicate_ones(df): 
    '''
    This function detects consecutive 1s in the 'A' column 
    and delete the rows corresponding to all but the first 1 in 
    each group of consecutive 1s.
    '''
    mask = df['A'] == 1
    duplicates = mask & mask.shift(-1)
    df = df[~duplicates.shift().fillna(False)]
    df = df.reset_index(drop=True)
    return df

(注:同时附上了原始数据、curve_shift偏移-2后、delete_duplicate_ones处理后的图表)


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:17:35