首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在分组数据python中执行for循环?

如何在分组数据python中执行for循环?
EN

Stack Overflow用户
提问于 2021-04-09 01:40:11
回答 2查看 49关注 0票数 0

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

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

然后,for循环应该检查每一行以查看高度变化是否大于30英尺,如果是这样的话,应该从该行开始分配一个'TRUE‘直到着陆(高度= 0)。

然而,当我使用包含不同飞机id的数据帧时,这个for循环似乎不起作用。

代码语言:javascript
复制
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

有什么建议吗?

EN

回答 2

Stack Overflow用户

发布于 2021-04-09 02:20:26

代码末尾的for循环只对df的第0行执行条件检查。for循环末尾的break应该在那里吗?

票数 0
EN

Stack Overflow用户

发布于 2021-04-09 02:37:21

我不认为有必要:

创建一个初始值为False的新列df‘’aborted_landing‘= False

和for循环。

只需执行df['aborted_landing]= df['altitude_climb'] >30

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67009193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档