Link_tester
Link_tester

Reputation: 1081

How to put multiple conditions (one or and two and) in np.where function

I have a numpy array of several rows and three columns. I want to do a np.where function to find two rows among all the existing rows. The first row I want is the row that has the least values of the second column and also its third column is the minimum one among others. The second row is among the rows that have the highest values in their second column. And my target has the least value of in its third column among these rows. It is my data set:

arr=np.array([[6. , 1. , 1.2],
              [5.5, 3. , 1.5],
              [5. , 1. , 2. ],
              [5. , 3. , 2. ],
              [5. , 6. , 2. ],
              [4. , 1. , 3. ],
              [4. , 3. , 3. ],
              [4. , 6. , 3. ],
              [3. , 1. , 4. ],
              [3. , 3. , 4. ],
              [3. , 6. , 4. ]])

Then I tried using two & and one |:

arr[np.where(((arr[:,1]==min(arr[:,1])) & (arr[:,-1]==min(arr[:,-1]))) |
             ((arr[:,1]==max(arr[:,1])) & (arr[:,-1]==min(arr[:,-1]))))]

To get the

np.array([[6. , 1. , 1.2], [5. , 6. , 2. ]]

But it is only giving me:

np.array([[6. , 1. , 1.2]]

I do appreciate any help to solve my problem.

Upvotes: 0

Views: 88

Answers (2)

Daniel Konstantinov
Daniel Konstantinov

Reputation: 411

a1 = arr[:, 1]
a2 = arr[:, 2]
a1mn = a1.min()
a1mx = a1.max()
ia1mn = (a1 == a1mn)
ia1mx = (a1 == a1mx)

out = arr[(ia1mn & (a2 == a2[ia1mn].min())) | (ia1mx & (a2 == a2[ia1mx].min()))]

Upvotes: 1

Virtuoz
Virtuoz

Reputation: 914

This should work as you expected

arr1 = arr[arr[:,1]==min(arr[:,1])]
arr1 = arr1[(arr1[:,-1]==min(arr1[:,-1]))]

arr2 = arr[(arr[:,1]==max(arr[:,1]))]
arr2 = arr2[(arr2[:,-1]==min(arr2[:,-1]))]

np.concatenate([arr1, arr2])

Upvotes: 1

Related Questions