gpt4 book ai didi

python - 总结特定(多个)范围的数据

转载 作者:行者123 更新时间:2023-11-28 21:31:56 24 4
gpt4 key购买 nike

我确信有一个很好的方法可以做到这一点,但我在谷歌上找不到正确的搜索词,所以我会在这里问。我的问题是这样的:

我有 2 个二维数组,它们都具有相同的维度。一个数组(数组 1)是 (x,y) 点的累积降水量。另一个(数组2)是同一(x,y)网格的地形高度。我想对数组 2 的特定高度之间的数组 1 求和,并创建一个条形图,其中 x 轴为地形高度箱,y 轴为总累积降水量。

所以我希望能够声明一个高度列表(例如[0, 100, 200, ..., 1000]),并且对于每个箱,总结发生在其中的所有降水那个垃圾箱。

我可以想到一些复杂的方法来做到这一点,但我猜可能有一种我没有想到的更简单的方法。我的直觉是循环遍历我的高度列表,掩盖该范围之外的任何内容,总结剩余的值,将它们添加到新数组中,然后重复。

我想知道是否有内置的 numpy 或类似的库可以更有效地完成此操作。

最佳答案

此代码显示了您所要求的内容,注释中有一些解释:

import numpy as np


def in_range(x, lower_bound, upper_bound):
# returns wether x is between lower_bound (inclusive) and upper_bound (exclusive)
return x in range(lower_bound, upper_bound)


# vectorize allows you to easily 'map' the function to a numpy array
vin_range = np.vectorize(in_range)

# representing your rainfall
rainfall = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# representing your height map
height = np.array([[1, 2, 1], [2, 4, 2], [3, 6, 3]])
# the bands of height you're looking to sum
bands = [[0, 2], [2, 4], [4, 6], [6, 8]]

# computing the actual results you'd want to chart
result = [(band, sum(rainfall[vin_range(height, *band)])) for band in bands]

print(result)

倒数第二行是奇迹发生的地方。 vin_range(height, *band) 使用向量化函数创建 bool 值的 numpy 数组,其维度与 height 相同,如果值为 ,则值为 True >height 在给定的范围内,否则False

通过使用该数组用目标值 (rainfall) 索引数组,您将获得一个仅包含高度在目标范围内的值的数组。然后只需将这些相加即可。

result = [(band, sum(rainfall[vin_range(height, *band)])) for band in band] 的步骤更多(但结果相同):

result = []
for lower, upper in bands:
include = vin_range(height, lower, upper)
values_to_include = rainfall[include]
sum_of_rainfall = sum(values_to_include)
result.append(([lower, upper], sum_of_rainfall))

关于python - 总结特定(多个)范围的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318215/

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