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

如何计算Numpy数组中正、负、零值的最大连续出现次数

NumPy数组连续值最大序列长度计算实现

核心实现代码

直接运行下方代码即可得到和预期完全匹配的统计结果:

import numpy as np

# 定义题目给定的原始数组
a = np.array([  0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0.,
   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,   0. ,  -8. ,   0. ,   0.,
 304.2, -27.8, -15.4,   0. ,   0. , -14.8,   0. ,   6.4,  14.4,   0. , -10.6,  55.8,
  23.1,   0. ,  27.9,  34.7,  62. ,  23. ,  41.6,  30.7,  30.5,  34.9,  40.9,  21.7,
  31.3,  19.9,  32.8,  26.2,  14.8,  18.9,  15.2,  23.8,  21.9, 112.7,  38.4,  34.4])

# 生成元素类别标签:正值=1、零值=0、负值=-1
category = np.sign(a)

# 定位类别发生变化的所有断点位置
break_points = np.where(np.diff(category) != 0)[0] + 1

# 计算每一段连续同类别序列的长度
seg_lengths = np.diff(np.concatenate([[0], break_points, [len(a)]]))
# 提取每一段对应的类别标签
seg_cats = category[np.concatenate([[0], break_points])]

# 按类别提取最大连续长度
max_con_pos = seg_lengths[seg_cats == 1].max()
max_con_zero = seg_lengths[seg_cats == 0].max()
max_con_neg = seg_lengths[seg_cats == -1].max()

# 输出结果
print(f"Consecutive Positive results: {max_con_pos}")
print(f"Consecutive Zero results: {max_con_zero}")
print(f"Consecutive Negative results: {max_con_neg}")

运行输出

Consecutive Positive results: 22
Consecutive Zero results: 21
Consecutive Negative results: 2

逻辑说明

  • 全程采用NumPy向量化操作,无逐元素遍历循环,对大尺寸数组的计算效率远高于纯Python循环实现
  • 用np.diff()完成类别突变检测,自动覆盖数组开头、结尾的分段,不会漏算首尾的连续序列
  • 分段长度计算时通过拼接首尾索引的方式修正偏移问题,避免索引错位导致的统计误差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 06:15:11