提取二维numpy数组索引的外部索引边界



我有一个100 × 100的2D numpy数组。我也有这个数组的下标。有什么方法可以提取或获得唯一索引吗?沿着阵列的每一边?(北行、东行、西行、南行)?下面是我的代码尝试,但是有些地方是错误的,因为每侧索引列表的大小是99,但它不是,有时在我的实际大数据上生成错误的索引!有没有更好的可靠的方法来做这项工作,而不会产生错误的结果?

import numpy as np

my_array = np.random.rand(100, 100)

indexes = np.argwhere(my_array[:, :] == my_array[:, :])
indexes = list(indexes)
NBound_indexes = np.argwhere(my_array[:, :] == my_array[0, :])
NBound_indexes = list(NBound_indexes)
SBound_indexes = np.argwhere(my_array[:, :] == my_array[99, :])
SBound_indexes = list(SBound_indexes)
WBound_indexes = []
for element in range(0, 100):
#print(element)
WB_index = np.argwhere(my_array[:, :] == my_array[element, 0])
WB_index = WB_index[0]
WBound_indexes.append(WB_index)


EBound_indexes = []
for element in range(0, 100):
#print(element)
EB_index = np.argwhere(my_array[:, :] == my_array[element, 99])
EB_index = EB_index[0]
EBound_indexes.append(EB_index)
outet_belt_ind = NBound_indexes
NBound_indexes.extend(EBound_indexes) #, SBound_index, WBound_index)
NBound_indexes.extend(SBound_indexes)
NBound_indexes.extend(WBound_indexes)
outer_bound = []
for i in NBound_indexes:
i_list = list(i)
outer_bound.append(i_list)

outer_bound = [outer_bound[i] for i in range(len(outer_bound)) if i == outer_bound.index(outer_bound[i]) ]

这不会直接从my_array中提取它们,但您可以使用列表推导式生成与上述代码类似的结果:

y, x = my_array.shape
WBound_indexes = [np.array((i, 0)) for i in range(1, y-1)]
EBound_indexes = [np.array((i, x-1)) for i in range(1, y-1)]
NBound_indexes = [np.array((0, i)) for i in range(x)]
SBound_indexes = [np.array((y-1, i)) for i in range(x)]
outer_bound = NBound_indexes + WBound_indexes + SBound_indexes + EBound_indexes

例如,WBound_indexes看起来像:

[array([1, 0]), array([2, 0]), ..., array([97,  0]), array([98,  0])]