首页 > 解决方案 > 如何对涉及两个数据帧的条件的熊猫行迭代进行矢量化?

问题描述

我有两个数据框df1df2. 我需要迭代df1行以获取时间戳,并根据此时间戳+- 1000 milliseconds过滤来自df2. 下面的代码片段清楚地解释了它,

dataframes = []
for i in df1.index:
    tempdf = df1[df1.index.values == i]

    attributeName = tempdf['EventId'].iloc[0]
    timeStamp = tempdf['Timestamp'].iloc[0]
    fehlerStatus = tempdf['FehlerStatus'].iloc[0]
  
    tempdf2 = df2[(df2['DateTime']>=timeStamp + datetime.timedelta(milliseconds=0)) & 
                        (df2['DateTime']<=timeStamp + datetime.timedelta(milliseconds=1000))].sort_values(by='DateTime', ascending=True).reset_index(drop=True)
    if not tempdf2.empty:
        tempdf2['TargetAttributePlusStatus'] = attributeName.replace(' ', '_') + fehlerStatus.replace(' ', '_')
        dataframes.append(tempdf2)

df = pd.concat(dataframes, axis=0)

上面的代码需要永远执行。有没有更方便的方法来矢量化它?

标签: pythonpandas

解决方案


推荐阅读