You need to enable JavaScript to run this app. 按Distance累计≥10条件计算DataFrame中Slope列的代码修正
优惠活动
大模型
产品
解决方案
定价
更多

按Distance累计≥10条件计算DataFrame中Slope列的代码修正

按累计距离分组计算坡度方案

需求规则

现有包含Altitude、Distance、Slope三列的DataFrame,需通过前两列计算Slope列值,计算规则如下:

  • 从Distance列首行开始累加,累加和≥10时触发一次计算
  • 单组坡度计算公式:Slope = (当前分组内Altitude末值 - 当前分组内Altitude初值) / 当前组Distance累计和
  • 当前组计算完成后,重置累加器,从下一行开始重新累加Distance,重复上述逻辑直到所有行处理完毕,最后一组即使累计和不足10也需完成计算

逻辑示意:
逻辑示意图

实现代码

原参考代码采用累加海拔求均值的KM_mean逻辑,不符合首尾海拔差值的计算要求,修正后代码如下:

import pandas as pd

# 示例数据
data = [
[11.2,     0],
[11.2,     3.018],
[10.9,     4.18],
[10.1,     4.873],
[9.9 ,     5.499],
[9.4 ,     5.923],
[9.2 ,     6.415],
[8.5 ,     1.063],
[8.4 ,     1.667],
[7.9 ,     3.114]
]

df = pd.DataFrame(data, columns=['Altitude','Distance'])
# 初始化Slope列
df['Slope'] = 0.0

# 初始化分组参数
sum_dist = 0
start_idx = 0
start_alt = df.loc[start_idx, 'Altitude']

for i in range(df.shape[0]):
    sum_dist += df.loc[i, 'Distance']
    # 触发计算:累计距离达标 或 遍历到最后一行
    if sum_dist >= 10 or i == df.shape[0] - 1:
        # 计算当前组坡度
        current_slope = (df.loc[i, 'Altitude'] - start_alt) / sum_dist
        # 给当前组所有行赋值坡度
        df.loc[start_idx:i, 'Slope'] = current_slope
        # 重置参数开启下一组
        if i != df.shape[0] - 1:
            start_idx = i + 1
            start_alt = df.loc[start_idx, 'Altitude']
            sum_dist = 0

# 输出结果
print(df)

内容的提问来源于stack exchange,提问作者Allin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 07:36:03