python - 两个二维数组从哪里开始相互重叠?

标签 python multidimensional-array numpy subdomain overlap

我目前正在处理模型输出,但我似乎无法想出一种组合两个数据数组的好方法。数组 A 和 B 存储不同的数据,每个条目对应一些空间 (x,y) 点——A 保存一些参数,B 保存模型输出。问题是 B 是 A 的空间子部分——也就是说,如果模型适用于整个世界,A 将存储地球上每个点的参数,而 B 将只存储非洲那些点的模型输出.

所以我需要找到 B 从 A 偏移了多少——换句话说,我需要找到它们开始重叠的索引。那么如果 A.shape=(1000,1500),B 是其中的 (750:850, 200:300) 部分,还是 (783:835, 427:440) 小节?我有与 A 和 B 相关联的数组,它们存储每个网格点的 (x,y) 位置。

这似乎是一个简单的问题——找到两个数组重叠的地方。我可以用 scipy.spatial 的 KDTree 简单地解决它,但它非常慢。谁有更好的想法?

最佳答案

I have arrays associated with both A and B which store the (x,y) positions of the gridpoints for each.

在那种情况下,答案应该相当简单......

这两个网格是否严格遵循相同的网格化方案?假设它们是,您可以执行以下操作:

np.argwhere((Ax == Bx.min()) & (Ay == By.min())) 

假设两个网格的世界坐标在与网格的索引相同的方向上增加,这给出了子集网格的左下角。 (如果它们不沿同一方向增加(即负 dxdy),它只会给出其他角之一)

在下面的示例中,我们显然可以根据 ix = (Bxmin - Axmin)/dx 等计算适当的指标,但假设您有一个更复杂的网格系统,这仍然有效.然而,这是假设两个网格在相同的网格化方案上!如果它们不是...,情况会稍微复杂一些。

import numpy as np

# Generate grids of coordinates from a min, max, and spacing
dx, dy = 0.5, 0.5

# For the larger grid...
Axmin, Axmax = -180, 180
Aymin, Aymax = -90, 90

# For the smaller grid...
Bxmin, Bxmax = -5, 10
Bymin, Bymax = 30, 40

# Generate the indicies on a 2D grid
Ax = np.arange(Axmin, Axmax+dx, dx)
Ay = np.arange(Aymin, Aymax+dy, dy)
Ax, Ay = np.meshgrid(Ax, Ay)

Bx = np.arange(Bxmin, Bxmax+dx, dx)
By = np.arange(Bymin, Bymax+dy, dy)
Bx, By = np.meshgrid(Bx, By)

# Find the corner of where the two grids overlap...
ix, iy = np.argwhere((Ax == Bxmin) & (Ay == Bymin))[0]

# Assert that the coordinates are identical.
assert np.all(Ax[ix:ix+Bx.shape[0], iy:iy+Bx.shape[1]] == Bx) 
assert np.all(Ay[ix:ix+Bx.shape[0], iy:iy+Bx.shape[1]] == By) 

关于python - 两个二维数组从哪里开始相互重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4150909/

相关文章:

python - 对于小数组,Numpy 的分区比排序慢

python - python - 从另一个线程启动后将systrace处理程序添加到python线程的方法?

python - Numpy 从 3d 数组中删除列

python - 如何识别数据帧中的one-hot编码列

javascript - 在javascript中初始化 'multidimensional'对象

c# - 如何搜索多维数组?

python - 仅在数据框中计算几列的 LOG10

python - 使用 Python twisted 在 linux 上将 HID 访问与 evdev 集成

python - 什么是 Vaex 函数将字符串解析为 datetime64,相当于 pandas to_datetime,允许自定义格式?

python - 大量 NDB 实体的更新失败