I want to compare the minimum value of each row with the nearby elements. For example, min of first row occurs at Pe[0,1]. I want to compare this value with Pe[0,0], Pe[0,2] and Pe[1,1] and find the minimum amongst these three. Similarly for other rows. How to code it?
import numpy as np
Pe=np.array([[0.97300493, 0.4630001 , 0.66754101],
[0.09043881, 0.03976944, 0.64823791],
[0.9530546 , 0.40305156, 0.20944696]])
Pe_min=Pe.argmin(axis=1)
>Solution :
You can do this by looping over your rows, but it’s a bit tedious, I’m sure there’s a smarter way:
import numpy as np
a = np.array([[0.97300493, 0.4630001 , 0.66754101],
[0.09043881, 0.03976944, 0.64823791],
[0.9530546 , 0.40305156, 0.20944696]])
b = np.zeros((a.shape[0], 2))
for row_n, row in enumerate(a):
# Get row min
b[row_n][0] = np.min(row)
# Get surroundings min
i = np.argmin(row)
near = []
if row_n > 0:
near.append(a[row_n-1][i])
if row_n+1 < b.shape[0]:
near.append(a[row_n+1][i])
if i > 0:
near.append(a[row_n][i-1])
if i+1 < b.shape[1]:
near.append(a[row_n][i+1])
b[row_n][1] = min(near)
print(b)
# array([[0.4630001 , 0.03976944],
# [0.03976944, 0.09043881],
# [0.20944696, 0.40305156]])