【发布时间】:2022-01-07 08:44:21
【问题描述】:
我正在寻找一种方法,将 2D 数组中的每个值与其周围的值进行比较,并返回哪些值接近感兴趣的值(在阈值内)。
我探索的方法涉及遍历 2D 数组的每个元素,但我觉得这不是最快或最佳的方法。
输入将是一个 2D 数组(大小:ixj),输出将是两个 3D 数组(kxixj),其中“额外”维度用于存储 a 内附近元素的 i 和 j 索引阈值。
一些代码来说明我现在在做什么:
import numpy as np
from tqdm import tqdm
np.random.seed(seed=10)
arr = np.random.random((100, 100)) # Some 2D input array
threshold = 0.5
# Arrays for the row and col indices
i_all, j_all = np.mgrid[0:arr.shape[0],
0:arr.shape[1]]
# Footprint around the current element (ie looking at the 8 elements around the central value). Must be odd.
footprint = (3, 3)
footprint_size = np.product(footprint)
# Prepare output for i and j indices
output_i = np.full((footprint_size, *arr.shape), np.nan)
output_j = np.full((footprint_size, *arr.shape), np.nan)
for p, element in enumerate(tqdm(arr.flatten())): # Iterate through each element
i, j = np.unravel_index(p, arr.shape)
# Create mask of elements to compare to
mask = ((i_all >= (i - (footprint[0] - 1) / 2)) &
(i_all <= (i + (footprint[0] - 1) / 2)) &
(j_all >= (j - (footprint[1] - 1) / 2)) &
(j_all <= (j + (footprint[1] - 1) / 2)))
# Create mask of those within the threshold
close_mask = abs(arr[mask] - element) <= threshold
if np.nansum(close_mask) < np.product(footprint): # If at edges need to pad to be able to index into output arrays
output_i[:, i, j] = np.pad(i_all[mask][close_mask].flatten().astype(float),
(int(footprint_size - np.nansum(close_mask)), 0),
mode='constant', constant_values=np.nan)
output_j[:, i, j] = np.pad(j_all[mask][close_mask].flatten().astype(float),
(int(footprint_size - np.nansum(close_mask)), 0),
mode='constant', constant_values=np.nan)
else: # Don't need to pad here
output_i[:, i, j] = i_all[mask][close_mask]
output_j[:, i, j] = j_all[mask][close_mask]
# Output: two 3D arrays of indices corresponding to elements within the threshold of the element of interest for rows and cols
这适用于小型数组,但当数组有 ~10^6 个元素时非常慢。我的另一个想法是在自身上滑动数组以比较值。这可能会更快,但我很好奇是否有任何其他想法或内置函数可以做类似的事情。
【问题讨论】:
-
一种或另一种方式,您将遍历数组的每个元素。贴出你探索过的方法的代码,并指出你不喜欢它的地方或者为什么它不起作用以获得更详细的答案。
-
我已经编辑添加了一些代码来说明我现在正在做什么。
-
你的输出必须是指定的格式吗?也许每个邻居都有一个只有真/假(接近/不接近)的 8x100x100 矩阵会更容易
-
@dankal444 是的,它可能会,虽然我猜这需要存储有关搜索窗口大小的信息
标签: python arrays numpy multidimensional-array