Reputation:
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)
Upvotes: 0
Views: 81
Reputation: 42143
You could get a vectorized solution in 4 steps by assigning the minimums with shifted sub ranges on the previous and next rows/columns:
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]])
r = a.copy()
r[:,:-1] = np.minimum(r[:,:-1],a[:,1:]) # min with next columns
r[:,1:] = np.minimum(r[:,1:],a[:,:-1]) # min with previous columns
r[:-1,:] = np.minimum(r[:-1,:],a[1:,:]) # min with next rows
r[1:,:] = np.minimum(r[1:,:],a[:-1,:]) # min with previous rows
print(r)
[[0.09043881 0.03976944 0.4630001 ]
[0.03976944 0.03976944 0.03976944]
[0.09043881 0.03976944 0.20944696]]
Upvotes: 1
Reputation: 3485
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]])
Upvotes: 0