gpt4 book ai didi

python - numpy数组中两组值之间的距离

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:44 29 4
gpt4 key购买 nike

我有一个非常基本的问题,理论上很容易做到(在 ArcGIS 中点数较少,人工劳动很多),但我根本无法从编码开始解决这个问题(我也是复杂的 Python 编码的新手)。

我有 2 个变量“Root zone”又名 RTZ 和“Tree cover”又名 TC 都是 250x186 值的数组(它们基本上是网格,每个网格都有特定值)。 TC 中的值从 0 到 100 不等。每个网格大小为 0.25 度(可能有助于理解距离)。

我的问题是“我想计算范围在 50-100 之间的每个 TC 值的距离(因此在每个 latlon) 从最近的 TC 范围在 0-30 之间(小于 30)的点开始。"

请注意我们没有查看 TC 的 np.nan 部分。所以TC中的白色部分在RZS中也是白色的。 enter image description here

我想要做的是创建一个二维散点图,其中 X 轴表示“50-100 TC 与 0-30 值的距离”,Y 轴表示“RZS 那 50-100 个 TC 点'。上图可能会让事情更清楚。

我希望我可以为此提供任何代码,但我什至无法开始处理距离问题。请提供任何关于我应该如何进行的建议。

让我们考虑一个例子:如果您查看 x: 70 和 y: 70,可以看到很多点的值从树的 0-30 覆盖整个数据集。但我只想要从最近的值到我的点的距离,该距离在 0-30 之间。

最佳答案

以下代码可能适用于随机示例数据:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# Create some completely random data, and include an area of NaNs as well
rzs = np.random.uniform(0, 100, size=(250, 168))
tc = np.random.lognormal(3.0, size=(250, 168))
tc = np.clip(tc, 0, 100)
rzs[60:80,:] = np.nan
tc[60:80,:] = np.nan

plt.subplot(2,2,1)
plt.imshow(rzs)
plt.colorbar()
plt.subplot(2,2,2)
plt.imshow(tc)
plt.colorbar()

enter image description here

现在做真正的工作:

# Select the indices of the low- and high-valued points
# This will results in warnings here because of NaNs;
# the NaNs should be filtered out in the indices, since they will
# compare to False in all the comparisons, and thus not be
# indexed by 'low' and 'high'
low = (tc >= 0) & (tc <= 30)
high = (tc >= 50) & (tc <= 100)
# Get the coordinates for the low- and high-valued points,
# combine and transpose them to be in the correct format
y, x = np.where(low)
low_coords = np.array([x, y]).T
y, x = np.where(high)
high_coords = np.array([x, y]).T

# We now calculate the distances between *all* low-valued points, and *all* high-valued points.
# This calculation scales as O^2, as does the memory cost (of the output),
# so be wary when using it with large input sizes.
from scipy.spatial.distance import cdist, pdist
distances = cdist(low_coords, high_coords)

# Now find the minimum distance along the axis of the high-valued coords,
# which here is the second axis.
# Since we also want to find values corresponding to those minimum distances,
# we should use the `argmin` function instead of a normal `min` function.
indices = distances.argmin(axis=1)
mindistances = distances[np.arange(distances.shape[0]), indices]
minrzs = rzs.flatten()[indices]

plt.scatter(mindistances, minrzs)

enter image description here

结果图看起来有点奇怪,因为由于网格 (1, sqrt(1^1+1^1), 2, sqrt(1^1+2^2), sqrt( 2^2+2^2), 3, 平方根(1^1+3^2), ...);这是因为两个 TC 值都是随机分布的,因此低值可能最终直接与高值相邻(并且因为我们正在寻找最小距离,所以大多数标绘点都是针对这些情况)。垂直分布是因为 RZS 值在 0 到 100 之间均匀分布。
这只是输入示例数据的结果,不能太代表真实数据。

关于python - numpy数组中两组值之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972307/

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