python - 如何在分组数据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
有什么建议么?
解决方案
我认为不需要:
创建一个以 False 作为初始值的新列 df['aborted_landing'] = False
和for循环。
做就是了df['aborted_landing]= df['altitude_climb'] >30
推荐阅读
- websocket - 当我们使用 websocket 单读采样器 JMeter 时如何捕获响应标签
- java - 导致 IOException 覆盖 catch 块
- node.js - 无法更新用户资料
- c - C 在链接中移动节点
- bash - Shell脚本:嵌套引号内的变量
- python - RBF 层 - 难以理解
- c# - 如何使用 linq 将 C# 数据表中日期时间列中的月份和年份与其他列追加
- pandas - 用平均值(或最小值/最大值)替换最接近的值,如果 id 的所有值都相等,则用 id 保留两行
- google-apps-script - 如何在 Google 表格中的给定时间(在同一行给出)保护单元格?
- solidity - 我试图编译这段代码不幸的是我通常会出错