gpt4 book ai didi

python - 如何根据模式从 2D NumPy 数组中提取 2D NumPy 子数组?

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

我有一个二维 NumPy 数组,如下所示:


Array=
[
[0,0,0,0,0,0,0,2,2,2],
[0,0,0,0,0,0,0,2,2,2].
[0,0,1,1,1,0,0,2,2,2],
[0,0,1,1,1,0,0,2,2,2],
[0,0,1,1,1,0,0,1,1,1],
[0,0,0,0,0,0,0,1,1,1]
]

我需要将非零元素数组显示为:

Array1:
[
[1,1,1],
[1,1,1],
[1,1,1]
]

Array2:
[
[2,2,2],
[2,2,2],
[2,2,2],
[2,2,2]
]

Array3:
[
[1,1,1],
[1,1,1]
]

有人可以帮我看看我可以使用什么逻辑来实现以下输出吗?我不能使用固定索引(如 array[a:b, c:d]),因为我创建的逻辑应该能够用于具有类似模式的任何 NumPy 数组。

最佳答案

这使用 scipy.ndimage.label 递归地识别断开连接的子数组。

import numpy as np
from scipy.ndimage import label

array = np.array(
[[0,0,0,0,0,0,0,2,2,2,3,3,3],
[0,0,0,0,0,0,0,2,2,2,0,0,1],
[0,0,1,1,1,0,0,2,2,2,0,2,1],
[0,0,1,1,1,0,0,2,2,2,0,2,0],
[0,0,1,1,1,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0]])
# initialize list to collect sub-arrays
arr_list = []

def append_subarrays(arr, val, val_0):
'''
arr : 2D array
val : the value used for filtering
val_0 : the original value, which we want to preserve
'''

# remove everything that's not the current val
arr[arr != val] = 0
if 0 in arr: # <-- not a single rectangle yet
# get relevant indices as well as their minima and maxima
x_ind, y_ind = np.where(arr != 0)
min_x, max_x, min_y, max_y = min(x_ind), max(x_ind) + 1, min(y_ind), max(y_ind) + 1
# cut subarray (everything corresponding to val)
arr = arr[min_x:max_x, min_y:max_y]
# use the label function to assign different values to disconnected regions
labeled_arr = label(arr)[0]
# recursively apply append_subarrays to each disconnected region
for sub_val in np.unique(labeled_arr[labeled_arr != 0]):
append_subarrays(labeled_arr.copy(), sub_val, val_0)

else: # <-- we only have a single rectangle left ==> append
arr_list.append(arr * val_0)

for i in np.unique(array[array > 0]):
append_subarrays(array.copy(), i, i)

for arr in arr_list:
print(arr, end='\n'*2)

输出(注意:修改后的示例数组):

[[1]
[1]]

[[1 1 1]
[1 1 1]
[1 1 1]]

[[1 1 1]
[1 1 1]]

[[2 2 2]
[2 2 2]
[2 2 2]
[2 2 2]]

[[2]
[2]]

[[3 3 3]]

关于python - 如何根据模式从 2D NumPy 数组中提取 2D NumPy 子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076269/

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