首页 > 解决方案 > 将数据框行中的值与前一行进行比较的最佳方法

问题描述

我有一个相当大的df,我需要将一列的差异与前一行中不同列的值相乘。我尝试过使用 iterrows 和 itertuples(令人惊讶的是 iterrows 稍微快了一点),但它并没有达到应有的速度。我想知道是否有更有效的方法来完成这项任务。

这是我到目前为止所拥有的,但我似乎还找不到更好的方法。

def make_decision(df, max_gap):


    make_decision = []
    new_decision = []

    df.sort_values(by=["start_time"])
    tod = df.iloc[0]["stop_time"]

    for row in df.itertuples(index=False):

        toa = row[df.columns.get_loc("start_time")]

        if toa - tod > max_gap:
            make_decision.append(row[df.columns.get_loc("id")])
            new_decision.append(make_decision)
            make_decision.clear()

        else:
            make_decision.append(row[df.columns.get_loc("id")])

        curr_tod = row[df.columns.get_loc("stop_time")]

        if tod < curr_tod:
            tod = curr_tod
       
    if make_decision:
        new_decision.append(make_decision)

    return new_decision 

标签: pythonpandasdataframe

解决方案


根据方向,您可以使用:

df['start_time'] - df.shift()['stop_time']

或者

df['start_time'] - df.shift(-1)['stop_time']

或互换start_timestop_time


推荐阅读