首页 > 解决方案 > 如何在分组数据python中执行for循环

问题描述

我一直在尝试不同的方法来检测中止着陆。在代码中,我使用 for 循环设置了几个条件,但它没有给我想要的结果。目标是在索引 2 和 4 处获得“真”值。

您可以在下面找到一个虚拟数据框。首先,我创建了新列来计算当前高度与该特定飞机的先前高度之间的差异。然后过滤掉 NA 值和极值。完成后,我创建了一个初始值为“FALSE”的新列。

然后,for 循环应检查每一行以查看高度变化是否大于 30 英尺,如果是这种情况,则应从该行开始分配“TRUE”直到着陆(高度 = 0)

但是,当我使用包含不同飞机 ID 的数据框时,这个 for 循环似乎不起作用。

df = pd.DataFrame({
        'aircraft':     ['1', '1', '1', '2','1','1' ,'2','3','2','3', '3'],
        'altitude':     [1000, 900, 1200, 1000, 1400, 0, 890, 1050, 750, 850, 700],
    })

    # Creating two new columns showing the difference in altitude between transmissions
    df["altitude_shift"] = df.groupby(['aircraft'])["altitude"].shift(1)
    df["altitude_difference"] = df["altitude"] - df["altitude_shift"]
    
    
    # Replacing the NaN values with 0
    df.replace(np.nan,0)
    df['altitude_difference'] = df['altitude_difference'].fillna(0)
    
    # Filtering out the negative values, showing only the points where the aircraft climbs during approach
    df["altitude_climb"] = np.where(df["altitude_difference"]<0,
                                             0, df["altitude_difference"])
    
    # Filtering out the extreme climb values
    df['altitude_climb'] = np.where(df['altitude_climb']>800,
                                              0, df['altitude_climb'])
    
    # Creating a new column with False as initial value
    df['aborted_landing'] = False
    
    # Creates True values if the aircraft gains more than 30 ft between alt reports
    # The elif statement checks if the aircraft is on ground
    for indices, row in df.iterrows():
        if df.at[indices, 'altitude_climb'] > 30:
            df.loc[indices:, 'aborted_landing'] = True
        elif df.at[indices, 'altitude'] <= 0:
            df.loc[indices:, 'aborted_landing'] = False
        break

有什么建议么?

标签: pythonpandasdataframefor-loop

解决方案


我认为不需要:

创建一个以 False 作为初始值的新列 df['aborted_landing'] = False

和for循环。

做就是了df['aborted_landing]= df['altitude_climb'] >30


推荐阅读