gpt4 book ai didi

python - 计算 Python 中多维数组中达到或超过阈值的次数

转载 作者:太空狗 更新时间:2023-10-30 02:43:12 24 4
gpt4 key购买 nike

我有一个从 netCDF 文件中引入的 numpy 数组,其形状为 (930, 360, 720),其组织形式为(时间、纬度、经度)。

在 930 个时间戳的每个纬度/经度对中,我需要计算该值达到或超过阈值“x”(例如 0.2 或 0.5 等)的次数,并最终计算百分比每个点都超过阈值,然后输出结果,以便稍后绘制。

我尝试了很多方法,但这是我最近的方法:

lat_length = len(lats) 

#where lats has been defined earlier when unpacked from the netCDF dataset

lon_length = len(lons)

#just as lats; also these were defined before using np.meshgrid(lons, lats)

for i in range(0, lat_length):
for j in range(0, lon_length):
if ice[:,i,j] >= x:
#code to count number of occurrences here
#code to calculate percentage here
percent_ice[i,j] += count / len(time) #calculation

#then go on to plot percent_ice

我希望这是有道理的!我将不胜感激任何帮助。我是用 Python 自学的,所以我可能会遗漏一些简单的东西。

现在是使用 any() 函数的时候吗?计算超过阈值的次数然后计算百分比的最有效方法是什么?

最佳答案

您可以将输入的 3D 数组与阈值 x 进行比较,然后沿第一个轴与 ndarray.sum(axis=0) 求和得到计数,从而得到百分比,就像这样 -

# Calculate count after thresholding with x and summing along first axis
count = (ice > x).sum(axis=0)

# Get percentages (ratios) by dividing with first axis length
percent_ice = np.true_divide(count,ice.shape[0])

关于python - 计算 Python 中多维数组中达到或超过阈值的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com