Aim
Aim

Reputation: 487

Perform an operation on a 2D array only if certain condition is meet

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

Answers (2)

Jan Kuiken
Jan Kuiken

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

P&#233;ter Le&#233;h
P&#233;ter Le&#233;h

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

Related Questions