You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pandas为DataFrame计算x日高点x_day_high新字段

首先确保已导入依赖库并运行你提供的测试数据生成代码得到df,直接使用下方代码即可计算得到符合要求的x_day_high字段:

# 提取每日最高价序列
high_series = df['High'].tolist()
x_day_high_list = []

for idx in range(len(high_series)):
    current_high = high_series[idx]
    consecutive_cnt = 0
    # 从当前行的前一行开始倒序遍历统计
    for pre_idx in range(idx - 1, -1, -1):
        if high_series[pre_idx] < current_high:
            consecutive_cnt += 1
        else:
            break
    x_day_high_list.append(consecutive_cnt)

# 新增字段
df['x_day_high'] = x_day_high_list

# 验证输出
print(df[['High', 'x_day_high']])

上述代码逻辑为:逐行读取每日最高价,从当前日期的前一天开始倒序统计连续低于当日最高价的天数,该天数即为x_day_high的取值;如果前一天的最高价高于当日最高价,直接计为0,完全匹配你给出的期望输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:36:03