Extracting Outer index boundaries of a 2D numpy array index

Question:

I have a 100 by 100 2D numpy array. and I also have the index of such array. Is there any way that I can extract or get the "unique indexes" along each side of the array? (North_Bound, East_Bound, West_Bound, South_Bound)? Below is my code attempt, but something is wrong as the size of each side index list be 99 but its not and sometimes generates erroneous indexes on my actual big data! Is there any better reliable way to do this job that would not generates wrong results?

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]) ]
Asked By: bluered_earth

||

Answers:

This wouldn’t extract them directly from my_array but you could use list comprehensions to generate similar results to your code above:

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

For example, WBound_indexes would look like:

[array([1, 0]), array([2, 0]), ..., array([97,  0]), array([98,  0])]
Answered By: sj95126
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.