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

如何从Python列表识别上升趋势?请求修正趋势判断逻辑

修正连续上升趋势检测的Python代码逻辑

我看了你的代码,发现两个核心问题导致没法正确识别你要的1-3月、9-12月连续上升趋势:

  1. 你错误地比较了月份字符串(input_data.iloc[index,0]取的是month列的文本值,比如'Jan'和'Feb'),而不是用来判断上升的count列数值
  2. 趋势结束后的记录逻辑不完整,循环结束后没有处理最后一段可能的上升趋势

下面是修正后的代码,能精准检测并输出连续上升的月份区间:

import pandas as pd

month=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']
count=[100,200,300,100,120,100,90,80,90,100,110,120]
dicta={'month':month,'count':count}
input_data=pd.DataFrame(dicta)
print(input_data)

# 存储连续上升的区间信息:(起始月份索引, 结束月份索引, 连续上升次数)
up_trends = []
current_up_length = 1  # 初始为1,单个数据点不算连续上升,连续递增从相邻两个开始累加

for index in range(len(input_data['count']) - 1):
    current_count = input_data['count'].iloc[index]
    next_count = input_data['count'].iloc[index+1]
    
    if next_count > current_count:
        current_up_length += 1
    else:
        # 当连续上升次数≥2时,说明至少有3个连续递增的点(比如Jan→Feb→Mar是2次上升,对应3个月)
        if current_up_length >= 2:
            start_idx = index - current_up_length + 1
            end_idx = index
            up_trends.append( (start_idx, end_idx, current_up_length) )
        # 重置当前连续上升长度
        current_up_length = 1

# 处理循环结束后,最后一段未被记录的上升趋势
if current_up_length >= 2:
    start_idx = len(input_data['count']) - current_up_length
    end_idx = len(input_data['count']) - 1
    up_trends.append( (start_idx, end_idx, current_up_length) )

# 格式化输出检测到的上升趋势
print("\n检测到的连续上升趋势:")
for trend in up_trends:
    start_month = input_data['month'].iloc[trend[0]]
    end_month = input_data['month'].iloc[trend[1]]
    print(f"{start_month} 到 {end_month}:连续 {trend[2]} 个月上升")

代码修改说明

  • 核心修正:把比较对象从月份字符串改成count列的数值,这是正确判断上升趋势的基础
  • 趋势跟踪:用current_up_length实时跟踪当前连续上升的长度,每次遇到不递增的情况就检查是否符合记录条件,然后重置
  • 补全逻辑:添加了循环结束后的检查,避免最后一段上升趋势(比如9-12月)被遗漏
  • 直观输出:最终直接对应到月份区间,方便你查看结果

运行这段代码后,你会得到预期的输出:

检测到的连续上升趋势:
Jan 到 Mar:连续 3 个月上升
Sept 到 Dec:连续 4 个月上升

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:32:46