1

I have a 2D numpy array that I need to extract a subset of data from where the value of the 2nd column is higher than a certain value. What's the best way to do this?

E.g. given the array:

array1 = [[1, 5], [2, 6], [3, 7], [4, 8]]

I would want to extract all rows where the 2nd column was higher than 6, so I'd get:

[3, 7], [4, 8]

3 Answers 3

2

Or, even more simply:

a[a[:,1] > 6]

Output:

array([[3, 7], [4, 8]])

Where a is the array.

Sign up to request clarification or add additional context in comments.

Comments

1

Use numpy.where:

import numpy as np

a = np.array([[1, 5], [2, 6], [3, 7], [4, 8]])
# all elements where the second item it greater than 6:
print(a[np.where(a[:, 1] > 6)])
# output: [[3 7], [4 8]]

Comments

1

Use list comprehension:

array1 = [[1, 5], [2, 6], [3, 7], [4, 8]]

threshold = 6
print([elem for elem in array1 if elem[1] > threshold])
# [[3, 7], [4, 8]]

Or using numpy:

import numpy as np

array1 = np.array(array1)
print(array1[array1[:,1] > 6])
# array([[3, 7], [4, 8]])

1 Comment

Does not really answer the question as it suggests the use of numpy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.