Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions np.extract

Tags:

python

numpy

I have an array and want ot extract all entries which are in a specific range

x = np.array([1,2,3,4])
condition = x<=4 and x>1
x_sel = np.extract(condition,x)

But this does not work. I'm getting

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

If I'm doing the same without the and and checking for example only one condition

x = np.array([1,2,3,4])
condition = x<=4 
x_sel = np.extract(condition,x)

everything works... Of courese I could just apply the procedure twice with one condition, but isn't there a solution to do this in one line?

Many thanks in advance

like image 783
Jan SE Avatar asked Aug 01 '26 23:08

Jan SE


1 Answers

You can use either this:

import numpy as np

x = np.array([1,2,3,4])
condition = (x <= 4) & (x > 1)
x_sel = np.extract(condition,x)
print(x_sel)
# [2 3 4]

Or this without extract:

x_sel = x[(x > 1) & (x <= 4)]
like image 173
Austin Avatar answered Aug 04 '26 15:08

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!