Reputation: 487
Consider the following 2D array:
A = array([[10, 5, 4, 2],
[11, 7, 6, 4],
[12, 4, 1, 2],
[13, 1, 6, 7],
[14, 2, 4, 5]])
I want to extract values that results after dividing second column by third column. But, this computation should be done only if the value in the first column is greater than 10 and less than 15. How can this be done?
Upvotes: 0
Views: 53
Reputation: 2010
You can create a mask
(array of booleans that can be used for indexing) to filter out rows with non complying first column values.
mask = np.logical_and(A[:,0] > 10, A[:,0] < 15)
This mask can be used to 'slice' the A
matrix
A[mask]
Then you can do the calculation on the sliced matrix
A[mask][:,1] / A[mask][:,2]
Upvotes: 1
Reputation: 2119
Something like this should work:
import numpy as np
A = np.array([[10, 5, 4, 2],
[11, 7, 6, 4],
[12, 4, 1, 2],
[13, 1, 6, 7],
[14, 2, 4, 5]])
# find the indices where the first column is between 10 and 15
idx = np.argwhere((A[:,0] > 10) & (A[:,0] < 15))
# divide the 2nd and 3rd column, then mask it with the preceding indices
(A[:,1] / A[:,2])[idx]
# array([[1.16666667],
# [4. ],
# [0.16666667],
# [0.5 ]])
Upvotes: 1