首页 > 解决方案 > 查找数组中的最大连续次数值小于阈值

问题描述

我有以下 numpy 数组 array([0.66594665, 0.33003433, NaN, 0.42567293, 0.48161913, 0.30000838, 0.13639367, 0.84300475, 0.19029748, NaN])

我想找到数组中的值连续小于 0.5 的次数。有没有办法在不使用 for 循环的情况下做到这一点?在此示例中,以下子序列的答案为 4:0.42567293, 0.48161913, 0.30000838, 0.13639367

标签: pythonnumpy

解决方案


import numpy as np

# Create a numpy array
arr = np.array([0.66594665, 0.33003433, np.nan, 0.42567293, 0.48161913, 0.30000838, 0.13639367, 0.84300475, 0.19029748, np.nan])

# Create a numpy array with consecutive values less than 0.5
arr_less_than_0_5 = np.where(arr < 0.5)[0]

# Print the array
print(arr_less_than_0_5)

# Get the number of consecutive times the values in a numpy array are less than 0.5
print(len(arr_less_than_0_5))

问题是给出值小于 0.5 的连续次数。它没有被要求打印特定的值。

所以这回答了你的问题


推荐阅读