I try to determine neighbors in a two-dimensional array using Python 3.7.
The array is like this:
array([[ 1., 2., nan, nan, 5.],
[nan, 2., nan, 5., nan],
[nan, 2., 4., nan, 6.],
[nan, nan, nan, 5., 5.],
[nan, nan, nan, nan, nan],
[ 1., 2., 4., nan, nan],
[ 1., 2., nan, nan, 4.],
[nan, 4., nan, nan, 5.]])
Firstly, the maximum value needs to be determined and the position is (2,4), then I want to get its neighbors with not nan values. The code is as follows:
test_arr = np.array([[1,2,np.nan,np.nan,5],
[np.nan,2,np.nan,5,np.nan],
[np.nan,2,4,np.nan,6],
[np.nan,np.nan,np.nan,5,5],
[np.nan,np.nan,np.nan,np.nan,np.nan],
[1,2,4,np.nan,np.nan],
[1,2,np.nan,np.nan,5],
[np.nan,4,np.nan,np.nan,6]])
row = test_arr.shape[0]
col = test_arr.shape[1]
temp_amatrix = np.matrix(test_arr)
p = np.argwhere(test_arr == np.nanmax(temp_amatrix)).flatten()[0]
q = np.argwhere(test_arr == np.nanmax(temp_amatrix)).flatten()[1]
def neighbours(test_arr_in,countnotnan_in):
for r in range(len(np.where(countnotnan_in==1)[0])):
x = np.where(countnotnan_in == 1)[0][r]
y = np.where(countnotnan_in == 1)[1][r]
indexlist = [[x-1,y-1],[x-1,y],[x-1,y+1],[x,y-1],[x,y+1],[x+1,y-1],[x+1,y],[x+1,y+1]]
for c in indexlist:
if 0 <= c[0] < row and 0 <= c[1] < col:
if np.isnan(test_arr_in[c[0],c[1]]) == False:
countnotnan_in[c[0],c[1]] = 1
return countnotnan_in
countnotnan = np.zeros_like(test_arr)
countnotnan[p][q] = 1
notnan_arr = neighbours(test_arr,countnotnan)
The result is:
notnan_arr = array([[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 1, 0],
[ 0, 0, 0, 0, 1],
[ 0, 0, 0, 1, 1],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]])
Yes, it is OK. Actually, I want to use the new '1' values to determine thier neighbors, i.e. determining the neighbors of (1,3), (3,3) and (3,4) positions. Repeat this process until all positions with values starting from the position of (2,4) are identified. The result will be this:
notnan_arr = array([[ 1, 1, 0, 0, 1],
[ 0, 1, 0, 1, 0],
[ 0, 1, 1, 0, 1],
[ 0, 0, 0, 1, 1],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]])
Next, I want to determine the maximum value of the rest unidentified value to repeat the process until all neighbors' position with values of this two-dimensional array are identified. And the final result should be like this:
notnan_arr = array([[ 1, 1, 0, 0, 1],
[ 0, 1, 0, 1, 0],
[ 0, 1, 1, 0, 1],
[ 0, 0, 0, 1, 1],
[ 0, 0, 0, 0, 0],
[ 1, 1, 1, 0, 0],
[ 1, 1, 0, 0, 1],
[ 0, 1, 0, 0, 1]])
My mother tongue is not English, if anyone has any question about the description. Please tell me, I will try my best to state it. And if anyone can help me, I would be very grateful.